Search code examples
swiftnsurlcache

How to load cache data at first and load data from network after


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?


Solution

  • 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. :-)