Authorization callbacks in Swift using Combine

Maciej Burdzicki
2 min readJul 6, 2021

--

Photo by Maxwell Nelson on Unsplash

Combine is a framework Apple introduced in 2019 that’s supposed to be Apple’s own recipe for reactive programming and probably, just like Swift substituted Objective-C on the market, Combine will substitute rxSwift rather sooner than later so it’s a good idea to learn it.

Combine vs rxSwift is not a subject of today’s article anyway so let’s talk authorization.

As you begin playing with Combine and taking advantage of how much easier it is to perform network requests thanks to dataTaskPublisher, you may start to wonder: “Cool, but how am I supposed to handle authorization callback with those publishers?”.

Here’s some sample UsersEndpoint.

Well, once you start setting up your publisher to properly handle the data you want to receive from an endpoint, each and every method you call in the process such as decode(), receive(on:), map() and flatMap() expects you to return some sort of Publisher. And that’s the key to everything.

Since you’re expected to always return some kind of Publisher when manipulating the output of your dataTaskPublisher’s response, nothing stops you from returning callback publisher in case of authentication failure, right? In order to add so, you may use flatMap.

Now it’s better but you still need to call your original publisher once again after you fetch/refresh your access token. You need to create a new method, prepareFetchUsersPublisher() for example and pass it in flatMap() of callbackPublisher.

And that’s it. Now, if your publisher fails, callback request will be handled automatically.

But it can be done easier…

You can achieve the same result with far less code and make your code easier to read even with many more requests if you use CombineNetworking. It’s a super easy to use framework made to work with Combine. You can learn how to use CombineNetworking by reading this article: https://neoth.medium.com/perform-network-requests-in-your-ios-app-easier-thanks-to-combinenetworking-9b3585252600

Meanwhile, here’s an example on how to setup automatic authorization callbacks handler.

Now you can fetch users easly like this.

That’s it. With CombineNetworking you can put URLRequest setup down to just setting up few variables of an enum implementing Endpoint protocol and make the whole thing far quicker to write and a whole lot easier to read and maintain.

Whether you prefer to use CombineNetworking or to perform network requests in some other way, I hope this article was helpful.

Thank you for your time and til the next one!

--

--

No responses yet