0

I am new to nsurlcache. And my goal is to show first my cache data and show it to my display and after that, I want to access the network and replace the cache data and reload my display.

This is what I'm using:

mutableURLRequest.cachePolicy = NSURLRequestCachePolicy.ReturnCacheDataElseLoad

Can someone help me or give me a better idea how to achieve my goal?

marcospereira
  • 12,045
  • 3
  • 46
  • 52
Alvin John
  • 403
  • 4
  • 14

1 Answers1

1

I think you want NSURLRequestReturnCacheDataDontLoad for the first fetch, then NSURLRequestUseProtocolCachePolicy for the second fetch.

Or you can ask the cache itself.

NSURLRequest *request = ...
NSCachedURLResponse *response = [[NSURLCache sharedURLCache] cachedURLResponseForRequest:request];

Not sure what the equivalent Swift code is, but hopefully the Objective-C is close enough to help. :-)

dgatwood
  • 10,129
  • 1
  • 28
  • 49
  • Hi @dgatwood, so I will request two times to achieve this? – Alvin John Sep 25 '16 at 02:32
  • Yeah. The first one to get the cached data and the second one to make the actual request over the wire. If you want to get stale data from the cache, you have to specifically ask for it, and by doing so, it won't ever contact the server. – dgatwood Sep 26 '16 at 01:51
  • I should also mention that lots of folks have tried this over the years, and usually they find that updating the content while a user is looking at it results in a bad user experience (unless the data is highly structured). In most situations, a better approach is to request the (potentially stale) cache data, start the request, start a timer, and if the response comes back before the timer fires, cancel the timer and show the real data. If not, show the cached data and let the request complete in the background, but don't show the new data until the user leaves the page and comes back. – dgatwood Sep 26 '16 at 01:57