Using NSURLCache to display data quickly, update in background

327 views Asked by At

I'd like my iOS application (at least certain endpoints) to have the following network behavior:

  • Always use the cache, whenever it's available, no matter the age (draw the UI right away)
  • If the data is stale, also make a network request (the UI has stale data during this period, but it's still probably pretty close)
  • If network data returns, update the cache and make any UI updates that are required.

I prefer a behavior like this because I can then set my caching policy very aggressively (long cache times). For data that updates infrequently, this results in rapid UI returns in the common case and a model layer that is kept up to date essentially in the background (from the user's perspective)

I'm reading about NSURLCache, but I don't see a cache policy, or even a combination of two policies that I'm confident in.

Options:

  1. Use ReturnCacheDataDontLoad to always get cache. If failure or old cache use ReloadIgnoringLocalCacheData for the HTTP fetch. (have to check myself? age is inspectable?)
  2. Use ReturnCacheDataDontLoad to always get cache. Then use UseProtocolCachePolicy with the cache time set to very low and ignore the response if it returns from cache (can I tell if it returns from cache? this says not reliably)
  3. Separate the two concerns. Use ReturnCacheDataDontLoad for all user-initiated requests, only firing a network request right away if there is no cache at all. Separately, have a worker that keeps an eye on stored models, updating them in the background whenever they appear old.
  4. Extend NSURLCache
  5. Use something OTS that already does this? (-AFNetworking just uses NSURLSession caching. +EVURLCache forces disk caching but expects the data to be seeded on app install.
0

There are 0 answers