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.
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Contents
Alamofire Tutorial for iOS: Advanced Usage
25 mins
- Getting Started
- Custom Session and URLSessionConfiguration
- Customizing Session
- Logging Network Requests and Responses Using Event Monitor
- GitHub Authorization
- OAuth Overview
- Creating GitHub OAuth App
- Logging Into GitHub
- Fetching User Repositories
- Request Overview
- RequestInterceptor Overview
- Integrating RequestInterceptor
- Routing Requests and URLRequestConvertible
- Network Reachability
- Caching Using ResponseCacher
- Where to Go From Here?
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:
- To cache requests for the session, you set
requestCachePolicy
onURLSessionConfiguration
toreturnCacheDataElseLoad
. Once set, the cache returns the response. If the cache doesn't have a response, a network request is made. - 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 theuserInfo
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.
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.