How to get cached responses using Alamofire while app is in offline?

5.2k Views Asked by At

After I got a response via Alamofire, in some cases, implementing a database or managing local storage myself (file etc.) can be a bit overkill.

I know about Alamofire's requestCachePolicy and it is already caching responses (based on cache-control's max-age), but this has more to do with reducing the number of requests/improve the experience when online.

But is it possible to use the cached response when I have no connection available via Alamofire? (Does Alamofire provide some kind of convenient way to handle this)

1

There are 1 best solutions below

1
On

For achieving this behaviour. You should try to modify the "on going" request is about to be perfomed and setting the flag returnCacheDataDontLoad or returnCacheDataElseLoad for getting the desired behaviour. (Depends of your needs)

Something like:

var req = URLRequest(url: URL(string: "http://foo.bar.com/res")!)
if noInternet {
    req.cachePolicy = .returnCacheDataDontLoad
}

Also make sure about the caching policies the app is negotiating with the server just in case you need to tweak it as well.

Hope it helps! :)