I want to cache the response of API. When the internet is available it should fetch data from the server and should update locally cached data every time and when the internet is not available it should show cached data. Is it possible with Alamofire or URLSession
? or do I need to use a database and I should manually handle this?
2
Answers
With
Alamofire
, It can be achieved as below,What if you did something like this using
URLRequest
Update based on OPs comment
Setting the
cachePolicy
toreloadIgnoringLocalCacheData
does not mean don’t store any data in cache, it means ignore anything stored in cache and get data from the source.Using the default
shared
singleton of URLSession makes use of a default cache as per the docsFrom the docs
Give this a try, I tried based on the use case you mentioned above and it does what you want it to do.