Today we are going to discuss “how to retry a request using Alamofire, an HTTP networking library written in Swift. In this tutorial, we will use Petfinder API on “https://www.petfinder.com/developers/” so you need to create an account on this website to get your personal “API Key” and “Secret” if you want to use this website API for your API calls. When you logged in, you have access to your “API Key” and “Secret” on the developer section of your account.

Image for post

“API Key” and “Secret”

You can also find a comprehensive description of how to use this API on “https://www.petfinder.com/developers/v2/docs/”.

Could you tell me “Where the problem exactly lies!”?

Okay, here we go. In the real world of iOS development if you want to get a proper response from your backend provider through API call you need something that identifies you are allowed to have access to these data. Although different providers may implement different algorithms for identification, using an access token is one of the most popular methods among them. So far we have investigated that we need something like an access token to get an appropriate response from the server and this will grant your access to the provider server. However; there are situations where your token expires and guess what, you will no longer get your desired response from the server. In this case, you send your request with the expired token to the server then your request fails and finally you have no result to update your user interface. In such cases, a logical approach is to retry the request which failed due to an expired token error but do not forget to refresh the access token before retrying the request.

Let’s track this from the beginning!

With your personal “API Key” and “Secret” obtained from the Petfinder website, you can send a request to get a token. Please note that this token will place in the header of your future requests to get animal details. Personally, I always create a network manager class which will be responsible for network calls and will pass the raw data in a completion handler. For the authorization purpose, we have to send a post request with the achieved API key and secret key from the Petfinder website.

login function in login view model class

As you can see in the above code, with perceived parameters from the shared instance of the network manager we call the authorize function and pass in the parameters. Then in the completion handler, if we have received data from the server, we map our results with JSONSerialization class to a dictionary to get a token from the response and save this token for future usage in the UserDefaults.

#api-call #ios-app-development #networking #ios #alamofire

Retry Request Using Alamofire
7.20 GEEK