URLSessionDataTask response from URLCache or not?

For Q&A and logging purposes, I need to know whether the response to an URLSessionDataTask comes from the URLCache or not.

I've read here and there that it was just a matter of comparing the cachedResponse before and after receiving the dataTask response. But it does not work as each call to URLCache.shared.cachedResponse(for: urlRequest) returns a new instance of CachedURLResponse (each one having another new instance of HTTPURLResponse).

Am I missing something? Is there another way to tell if the response comes from the cache?

(each one having another new instance of HTTPURLResponse).

Could you provide a brief example of how you are loading and saving your cached response?


Matt Eaton
DTS Engineering, CoreOS
meaton3@apple.com
First I create the URLRequest object with a cachePolicy (usually .useProtocolCachePolicy).
     var urlRequest = URLRequest(url: url, cachePolicy: cachePolicy, timeoutInterval: timeoutInterval)

Then I retrieve the cachedResponse from URLCache as follows:
     let cachedResponse = URLCache.shared.cachedResponse(for: urlRequest)

Here, cachedResponse(for:) always returns a new object (different pointer) if called several times with the same URLRequest. And it's the same for the HTTPURLResponse that I get as follows:
     let cachedHTTPURLResponse = cachedResponse?.response

Finally I create and resume the URLSessionDataTask, assuming the response will cached in URLCache (if the cache policy allows it).
     let dataTask = urlSession.dataTask(with: urlRequest) { ... }
     dataTask.resume()
Accepted Answer
One thing you could look at is using URLSessionTaskMetrics to determine if the URLRequest was used from the local cache.

Take a look at the following for more information:

Code Block swift
func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) {
for metric in metrics.transactionMetrics {
print("Metric: \(metric)")
switch metric.resourceFetchType {
case .localCache:
print("Resource was fetched from the local cache")
case .networkLoad:
print("Resource was fetched from the network")
case .serverPush:
print("Resource was a server push")
case .unknown:
print("Resource was unknown")
}
}
}



Matt Eaton
DTS Engineering, CoreOS
meaton3@apple.com
Thanks Matt for your support, this is exactly what I was looking for.

Side question: sometimes there are two transactions (the first one hitting the cache, the second one the network). I assume the first transaction finds out that the cached response is stale, hence the second transaction. If I'm correct, is there any property describing the cache transaction result?

Thanks again,
Aurélien.
URLSessionDataTask response from URLCache or not?
 
 
Q