简体   繁体   中英

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM