The end result I would like to achieve is to use cached data when the network is unavailable and load data from the server when the network is available.
The closest thing I've found is this thread, but I am still having trouble getting it to work using Alamofire. How to cache response in iOS and show only when internet is not available?
I have two classes, one to check the network status and another that configures an Alamofire url session. Detecting the network status seems to be working, but it's not changing the session configuration. What am I doing wrong? Thanks!
NetworkReachability.shared.startNetworkMonitoring() is run when the app loads in didFinishLaunchingWithOptions.
class NetworkReachability {
static let shared = NetworkReachability()
let reachabilityManager = NetworkReachabilityManager(host: "www.google.com")
func startNetworkMonitoring() {
reachabilityManager?.startListening(onUpdatePerforming: { status in
switch status {
case .notReachable:
ApiManager.configuration.requestCachePolicy = .returnCacheDataDontLoad
case .reachable(.cellular):
ApiManager.configuration.requestCachePolicy = .reloadIgnoringCacheData
case .reachable(.ethernetOrWiFi):
ApiManager.configuration.requestCachePolicy = .reloadIgnoringCacheData
case .unknown:
print("Unknown network state")
}
})
}
}
A custom api manager to configure the cache.
class ApiManager {
static let shared = ApiManager()
static let configuration = URLSessionConfiguration.af.default
public let sessionManager: Alamofire.Session = {
let responseCacher = ResponseCacher(behavior: .modify { _, response in
let userInfo = ["date": Date()]
return CachedURLResponse(
response: response.response,
data: response.data,
userInfo: userInfo,
storagePolicy: .allowed)
})
return Session(
configuration: configuration,
cachedResponseHandler: responseCacher)
}()
}