Retry API calls with Alamofire

How to handle failed requests?

Daljeet Seera
2 min readMay 18, 2020
Source: Google

Generally, applications face issues of poor connectivity or connection lost which ruins the end-user behavior if not handled properly. A lot of applications generally show an error message on the screen or through an alert.

Use Case

During the development of one of my recent projects, I came across this issue of giving flexibility to end-user for retrying the failed pages. I had to create something centralized which can be used everywhere in the app. I was using Alamofire for Network Request, so, I thought of writing a wrapper around this library itself.

I will demonstrate how to write API Request with retries using the Alamofire library.

Implementation

Let’s start it by configuring the Alamofire library in your project. Next, create one wrapper for your API calls and that should be common for your all network requests.

I have created a separate wrapper class for network request retries which is configured with session manager of Alamofire as seen above at line 7.

This wrapper takes care of your request retries, I have set the request count to 3 to keep trying until three times to get the results. If you don’t want any retries to your API requests then you can set the count to minimum 1.

Then, I have created one function for POST API calls with some custom parameters which you can pass in your request calls. This function returns the response in success or failure which I have used in the form of “Data” or “Network Error”.

It is also visible that I have added a reachability check before making API calls in order to avoid unnecessary calls to the network. One can show a retry option with an appropriate error message.

Conclusion

Hope, this article helps you to understand the use of retries with Alamofire. I have created one sample project using the Alamofire library. I have used this wrapper extensively and it has proven to be good so far for my use case. Suggestions or improvements are welcome.

Thanks for reading 🙌🏼

--

--