URLCache inspection
Some responses should be cached to reduce network traffic, speed up an app, or support offline mode. Other responses, especially the ones that contain sensitive info, should not be cached. So it makes sense to verify what's in the URLCache. If possible, before you get a pen-test report from a third-party ;)
We can use the URLCache's cachedResponse(for:)
API to check what is cached. But when I passed to the API the same URLRequest I passed to the dataTask(with:)
API, I got back a nil
.
With URLCache currentMemoryUsage
API I confirmed that the memory usage increased, so it was time to implement URLSessionDataDelegate
and its urlSession(_:dataTask:willCacheResponse:completionHandler:)
method to find out what's happening. But my delegate method was not called. It turned out it wouldn't get called if the content was retrieved with dataTask(with:completionHandler:)
or dataTaskPublisher(for:)
. I had to use the dataTask(with:)
API.
The delegate method revealed that the two properties of the dataTask, originalRequest
and currentRequest
, were not the same in my case. The originalRequest
was the same request I used when calling the dataTask(with:)
API, and the currentRequest
had additional headers and was used as a key for URLCache. Those additional headers came from
httpAdditionalHeaders
property of URLSessionConfiguration
.