Alamofire Tutorial for iOS: Advanced Usage | raywenderlich.com

In this tutorial, you’ll learn about the advanced usage of Alamofire. Topics include handling OAuth, network logging, reachability, caching and more.


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/11668143-alamofire-tutorial-for-ios-advanced-usage

Thanks a lot for this awesome tutorial that is way more practical and easy-to-digest than the official documentation.

Just one question about the following line:

configuration.requestCachePolicy = .returnCacheDataElseLoad

Is there any way to implement a caching policy that returns the cached data AND then reloads and refreshes the cache from the network at the same time, potentially calling the completion block twice?

I would like to use caching as a way to speed up the user experience by loading the cache but also there are some location-dependent elements in my data so I want to make sure that eventually, the user had the most up-to-date data.

Or is that just a bad idea, which would explain why there is no constant to do that?

Hi @sarbogast, I’m glad to hear you liked the tutorial. :]

Great question regarding caching. As you already knew, there is no returnCacheDataAndLoad cache policy provided by the Foundation framework. However, there are different ways you can consider approaching it:

  • Use persistent storage in the app, for example, a DB. Load the contents from the DB when the app loads and then subsequently make a network request to get up-to-date data.

  • If you want to utilize URL caching, then you can use the request modifier to set the corresponding cache policy per request.

For example:

  func makeApiCall(forceRefresh: Bool) {
    sessionManager.request("http://myurl") { request in
      if forceRefresh {
        request.cachePolicy = .reloadIgnoringCacheData
      } else {
        request.cachePolicy = .returnCacheDataElseLoad
      }
    }.responseDecodable(...)
  }

Here, based on theforceRefresh value, the corresponding cache policy of the request is set.

if forceRefresh is false, it’ll return cached data if it is available, else makes a network request.

if forceRefresh is true, it’ll fetch the data from the network by ignoring the cache.

You can call makeApiCall twice, once to load your data from the cache and display the contents in the UI and subsequently make the network request with force parameter set to true.

Hope this helps!

In the RequestInterceptor adapt function, in the Github case the token doesn’t expire. How can you handle the case where the token does expire and the method returns an HTTP 401? Can you make a fetchAccessToken call from inside the interceptor and then retry the call somehow?

1 Like