From the course: Learning Combine with Swift

Call REST APIs with DataTaskPublisher - Swift Tutorial

From the course: Learning Combine with Swift

Start my 1-month free trial

Call REST APIs with DataTaskPublisher

- We are ready to look at some practical use cases for Combine, starting with the most obvious, and that's to make URL requests. More specifically, making REST API requests using Combine. For that, we're making use of a familiar foundational framework library, URLSession, which you may be familiar with for downloading data previously. It contains an instance method that returns a publisher wrapping your URLRequest or simply given URL called DataTaskPublisher, which is convenient. Let's start with a simple example first: Instantiate a URLEndpoint. This endpoint mocks posts in JSON format. I then create a publisher instance to dataTaskPublisher, passing in the URL. Use our map operator to filter just the data. The publisher by default returns a tuple consisting of data and URL response. Next, we decode the response into a JSON object model, which we would have set up previously. It can either successfully pass down the pipeline a strongly formatted array of post objects or throw a failure error, which you will see shortly when we jump back into Xcode. If you wanted to pass in a request instead of a URL, you simply create a request instance and pass it in. Okay, so let's build out a simple call to get a list of posts. Jump into Xcode and enter our exercise files, and let's begin. I took the liberty of creating a post struct in Playgrounds, which simply maps out how the post object will look like. Note: it also conforms to Codable so that we can code and decode it. If you've worked with JSON responses before in Swift, this should look very familiar to you. To begin, let's go to line 18 to create a dataTaskPublisher. Enter the following: "let url = URL" and in parentheses enter "string: "https//jsonplaceholder.typicode.com/posts")" Enter: "let publisher = URLSession.shared.dataTaskPublisher" Enter in "url! .map{$0.data}" to get just the data. Next, we decode by entering ".decode" For type, you enter "Array<Post>.self" and for decoder, "JSONDecoder()" We will be getting back an array of post objects for this example. Now, we're going to create a subscription. Go to line 25 and enter "let cancellableSink = publisher .sink" For receiveCompletion, enter "{completion in" and on the next line enter "print(String(describing: completion))" For receiveValue, enter "{ value in" Enter "print("returned value \(value)" and now, we're ready to run this. Click on Run and you will see that we get back a single post returning a result decoded into our post struc. As you can see, interacting with APIs using Combine is quite straightforward, and more importantly, letting you think about how you consume data in a bit more of a declarative and different approach.

Contents