Search code examples
iosobjective-ccachingnsurlsessioncache-control

How to know if NSURLSessionDataTask response came from cache?


I would like to determine if the response from NSURLSessionDataTask came from cache, or was served from server

I'am creating my NSURLSessionDataTask from

request.cachePolicy = NSURLRequestUseProtocolCachePolicy;

Solution

  • Two easy options come to mind:

    • Call [[NSURLCache sharedURLCache] cachedResponseForRequest:request] before you make the request, store the cached response, then do that again after you finish receiving data, and compare the two cached responses to see if they are the same.
    • Make an initial request with the NSURLRequestReturnCacheDataDontLoad cache policy, and if that fails, make a second request with a more sane policy.

    The first approach is usually preferable, as the second approach will return data that exists in the cache even if it is stale. However, in some rare cases (e.g. an offline mode), that might be what you want, which is why I mentioned it.