Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)

like image 546
Jakub Truhlář Avatar asked Feb 25 '17 15:02

Jakub Truhlář


1 Answers

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! :)

like image 135
Ricowere Avatar answered Nov 06 '22 19:11

Ricowere