Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
like image 246
Peter Lapisu Avatar asked Dec 05 '16 14:12

Peter Lapisu


3 Answers

In order to know whether an URLSessionDataTask response comes from the cache or the network, you have to use a custom URLSession and provide it with an URLSessionTaskDelegate which has to implement the following method:

func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics)

You'll find very useful information in metrics, especially the list of transactions metrics for the request. Each transaction metrics has a property resourceFetchType which can either be .localCache, .networklLoad, .serverPush or .unknown.

More information here: Apple documentation regarding URLSessionTaskDelegate

like image 178
Aurelien Avatar answered Sep 25 '22 14:09

Aurelien


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.

like image 6
dgatwood Avatar answered Nov 13 '22 06:11

dgatwood


If your information need is only out of curiosity you can view your network usage the Xcode runtime network metics. Change the policy to a different setting and observe the difference.

like image 1
Chris Hinkle Avatar answered Nov 13 '22 05:11

Chris Hinkle