IDN Media Bevan Christian Jul 4, 2023

Leveraging Alamofire Interceptors in iOS: A Real-World Case Study

Article Summary

Bevan Christian uncovered why users were mysteriously logged out of a major startup's iOS app for years. The culprit? A homegrown token refresh mechanism that created race conditions nobody noticed.

This IDN Engineering case study walks through a real debugging journey in an iOS app using Alamofire. The author discovered that a custom refresh token implementation with a shared singleton was causing unexpected logouts when users made rapid API requests to different endpoints.

Key Takeaways

Critical Insight

Replacing custom token refresh logic with Alamofire's built-in RequestInterceptor eliminated years of mysterious user logouts by properly handling concurrent API requests.

The article includes the actual before and after code showing exactly how the interceptor's adapt and retry functions work together to prevent the logout bug.

About This Article

Problem

Bevan Christian's team found a bug in their token refresh mechanism. A shared boolean flag called hasBeenError lived in a Singleton NetworkService. When concurrent requests hit different endpoints, the flag would get stuck as true, which triggered unexpected forceUserRelog calls.

Solution

The team switched to Alamofire's RequestInterceptor protocol instead. They added .validate() to catch non-2xx status codes and built out the adapt() and retry() methods. This centralized the token refresh logic and let requests automatically retry with fresh tokens.

Impact

Moving away from the custom boolean flag to Alamofire's RequestInterceptor fixed a long-standing issue where users would get logged out unexpectedly. The new approach handles concurrent API requests properly without race conditions or needing manual retries.