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;
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
Two easy options come to mind:
[[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.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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With