I am about to start working on optimizing my app in regards to making HTTP requests as well as adding support for offline usage.
The general idea is that I want to make the app as smooth as possible without having the user to wait for network requests if the data is already available in cache.
This would be handled by the NSURLCache
out of the box if I set the Cache-Control
header for let's say a day. The problem is that the server resources sometimes change (on daily, weekly or monthly basis) and therefore the user would have old data. Yet, I still want the user not to have to wait for the data if there is at least something in the cache because there is a big chance that this data will be up-to-date.
Therefore I am thinking about implementing a following solution:
returnCacheDataDontLoad
reloadIgnoringLocalCacheData
1
and 3
4
Force load data from cache (Alamofire
):
let configuration = URLSessionConfiguration.default
configuration.requestCachePolicy = .returnCacheDataDontLoad
self.sessionManager = Alamofire.SessionManager(configuration: configuration)
sessionManager!.request(.....)
Force load data from server:
let configuration = URLSessionConfiguration.default
configuration.requestCachePolicy = .reloadIgnoringLocalCacheData
self.sessionManager = Alamofire.SessionManager(configuration: configuration)
sessionManager!.request(.....)
I would really appreciate if somebody could comment on the proposed solution and possibly criticize it or advice a difference solution as I really want to do this the right way.
Thank you in advance
As requested in the comments, here is the solutions I ended up with:
Rather than using NSURLCache
, I ended up writing my own 'caching layer' using Realm (link). They have a really nice API and basically you get the data syncing out of the box. They also have a concept of Realm notifications (observer pattern) where whenever your data changes, you get a callback with the diff.