Alamofire Tutorial for iOS: Advanced Usage

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

5 (23) · 3 Reviews

Download materials
Save for later
Share
You are currently viewing page 4 of 4 of this article. Click here to view the first page.

Caching Using ResponseCacher

Open GitAPIManager.swift. Remove the following configuration options in sessionManager:

configuration.timeoutIntervalForRequest = 30
configuration.waitsForConnectivity = true

Here, you remove the timeoutIntervalForRequest and waitsForConnectivity configuration options so the app doesn't wait for network connectivity.

Add the following below let configuration = URLSessionConfiguration.af.default in sessionManager:

//1
configuration.requestCachePolicy = .returnCacheDataElseLoad
//2
let responseCacher = ResponseCacher(behavior: .modify { _, response in
  let userInfo = ["date": Date()]
  return CachedURLResponse(
    response: response.response,
    data: response.data,
    userInfo: userInfo,
    storagePolicy: .allowed)
})

Here's a breakdown:

  1. To cache requests for the session, you set requestCachePolicy on URLSessionConfiguration to returnCacheDataElseLoad. Once set, the cache returns the response. If the cache doesn't have a response, a network request is made.
  2. Alamofire's ResponseCacher makes it easy to specify whether a request needs to get cached, not cached or modified before storing in the cache. Here you modify the response by specifying .modify, before saving into the cache. You save the response's date, in addition to the content of the response, by passing it in the userInfo dictionary.

Now update Session initialization in sessionManager as below:

return Session(
  configuration: configuration,
  interceptor: interceptor,
  cachedResponseHandler: responseCacher,
  eventMonitors: [networkLogger])

Here you pass responseCacher as cachedResponseHandler in the constructor of Session. This makes responseCacher handle the caching behavior for all the requests in Session.

Open AppDelegate.swift. Comment out the following line of code which starts network monitoring:

GitNetworkReachability.shared.startNetworkMonitoring()

This prevents the app from showing the No Network alert when it's offline. Turn off network access on the simulator or device. Build and run.

Logged in user repositories

Ta-da! You'll see the repositories loaded from the cache.

Congratulations! You're now an Alamofire pro. :]

Where to Go From Here?

Download the final project by clicking the Download Materials button at the top or bottom of the tutorial.

In this Alamofire tutorial, you learned how to:

  • Create a custom Session and URLSessionConfiguration.
  • Log network requests and responses using EventMonitor.
  • Handle authentication and retries using RequestInterceptor.
  • Configure a Router with URLRequestConvertible.
  • Check for network reachability using NetworkReachabilityManager.
  • Modify responses before caching using ResponseCacher.

To learn more, please check the Alamofire advanced usage documentation.

I hope you enjoyed this tutorial. If you have any questions or comments, please join the forum discussion below.