URLSession and the Combine framework

Tram Ho

Learn how to make HTTP requests and parse responses by using the new Combine framework with foundation networking.

API & data structure

First of all we will need some kind of API to connect, I will use the JSONPlaceholder service with the following data models:

Nothing special, just some basic codable elements, and a simple error, we want to show some errors if something fails. ❌

The traditional way

 

Making an HTTP request in Swift is quite easy, you can use the built-in URLSession shared with a simple data task, and have your response. Of course you might want to check for a valid status code, and if all goes well, you can parse your JSON response using the JSONDecoder objects from the Foundation.

Data tasks and the Combine framework

 

Now as you will see traditional “block-based” this approach is fine, but can we do something perhaps better here? You know, like describing the whole thing as a series, like we used to do this with Promises? Starting with iOS13 with the help of Combine frameworks you can really go further! ?

My favorite part of Combine is memory management & cancellation.

Data task with Combine

 

So the most common examples are usually:

  • First we create a cancellable for your Publisher
  • Then, we create a brand new data task publisher object
  • Map responseg, we only care about the data (ignore the error).
  • Decode the content of data with JSONDecoder
  • If anything goes wrong, just go with an empty array
  • Eliminate potential complexity to a simple AnyPublisher
  • Use the sink to display some information about the final value
  • Optional: you can cancel your network request at any time

Error handling

 

Please introduce some troubleshooting, because I don’t like the idea of ​​hiding errors. That’s a lot better to present a warning with actual error messages, right? ?

In a nutshell, this time we test the response code and if they get stuck we throw an error. Now, since the publisher can lead to an error state, the sink has a variation where you can check the results of the entire operation, so you can make your own thingy error there, as shown. display a warning. ?

Assign result to property

 

A common model is to store responses in an internal variable somewhere in the view controller. You can only do this using the assign function.

Very easily, you can also use the didSet to receive notifications about changes.

Group multiple requests

 

Sending multiple requests is one thing that used to be difficult. Now we have Compose and this task is just ridiculously easy with Publishers.Zip . You can literally combine multiple claimors and wait until both are finished. ?

Request dependency

 

Sometimes you have to load a resource from a certain URL, and then use that to extend the object with something else. I’m talking about dependency requests, which is pretty much a problem without Combine, but now you can chain two HTTP calls to each other with just a few lines of the following Swift code:

The trick is that you can flatMap a publisher into another.

Conclusion

 

Combine is a great framework, it can do a lot, but it certainly has some learning curve. Sadly, you can only use it if you are targeting iOS13 or higher so think before applying this new technology.

You should also note that currently (b6) does not have upload / downloadTaskPublisher, perhaps in a later beta seed we will see something like that. ?

Thank you for your interest in this article, which has been translated according to the article of the same name by Tibor Bödecs .

Share the news now

Source : Viblo