Refresh token and retry request using RxSwift

Tram Ho

Question

In iOS projects that use authenticator, login is often used with the access token after successfully logging in with the account and password. This approach is quite popular and widespread today. A typical situation is that if logging in and not using the app leads to the access token expiring (usually there will be a time limit), the application will pop out of the login screen and proceed to log in again. In this case, we often create an API refresh token to get the new access token, and immediately call back the old api so that we do not need to log in again. Or, automatically login if you kill the app without logging out. This action is to retry the API in case the api call is failed. Today I will guide everyone how to handle this situation on the RxSwift frameword using the AlamoreFire library.

Case Example

This happens when we:

  • Calling an API using the access token, but failed because the access token is out of date
  • Continue calling an API to refresh the access token with the aim of getting a new access token
  • Up to this step, there are two cases that happen:
  • One is that the API refreshes successfully, the new access token will be used to call the previous api, the app will run normally again (1)
  • The second case is that the API refresh is also faulty, so we need to continue handling, usually shoot back to the Login screen, force login again.

Handling expired tokens

We have the call function and get the data from the API as follows:

When the accesstoken expires, we use RxSwift’s retryWhen {} for processing. Call the API refresh token and save the new access token, then call the api again at first.

For this treatment we have to write a separate resfresh token function, to avoid infinite looping

Handling expired token refresh

The second situation occurs that the API refresh also fails, so we need to continue handling, usually shoot back to the Login screen, force login again. Then we only need to handle the error on the observale and call refreshToken

Above is the guide on how to handle your expired token, hopefully will help you handle a similar situation if you encounter it. Thanks for reading!

Share the news now

Source : Viblo