10

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)

Jakub Truhlář
  • 15,319
  • 7
  • 65
  • 73
  • Why don't use AwesomeCache pod, look this is the repo, https://github.com/aschuch/AwesomeCache i was working in one application with your requirement and I achieve with this pod, I hope this helps you – Reinier Melian Feb 25 '17 at 22:04
  • There are many libraries like this, but I'm not looking for 3rd party cache libraries. This kind of falls within the *managing local storage myself* part of my Q. – Jakub Truhlář Feb 25 '17 at 23:12
  • @JakubTruhlář . Hi, i am working alamofire swift 3 , i want cache the json object. Please guide me how to achieve this . Thank you – Uma Madhavi May 16 '17 at 05:37
  • From my understanding, this is the default behavior of Alamofire, since it is the default behavior of the underlying URLSession API. This documentation describes the default behavior: https://developer.apple.com/documentation/foundation/nsurlrequest/cachepolicy/useprotocolcachepolicy If you're still having issues, your server might not be returning the appropriate cache headers in the response, such as "Cache-Control". – Alex Machado Aug 22 '18 at 06:13

1 Answers1

1

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

Frye Lee
  • 15
  • 4
Ricowere
  • 671
  • 3
  • 7