1

For a GET request which is consistently the same (it has a query param too), I'm returning in the response this response header.

Cache-Control: max-age=3600, private

I'm creating a URLSession with this configuration. Basically, ensuring my cache is large. The URLSession persists throughout the life of the app and all requests go through it.

 var configuration = URLSessionConfiguration.default  
 let cache = URLCache(memoryCapacity: 500_000_000, diskCapacity: 1_000_000_000)
 configuration.urlCache = cache
 configuration.requestCachePolicy = .useProtocolCachePolicy

I create a data task with the completion handler:

let task = session.dataTask(with: request) { data, response, error in
     //... my response handling code here
}
task.resume()

There isn't anything complicated or unusual I'm doing. I'm now trying to optimise some calls with a caching policy.

So I have 2 issues:

  1. Requests that have no-cache policy are still being saved into the URLCache. Which I've confirmed by looking into the URLCache . Why is it caching them when the response explicitly states no-cache policy and I've told the session to use the protocol policy.

  2. On the request where I do want to use the cache, when I call session.dataTask on subsequent times, it never fetches from the cache. It always hits the server again - which I can confirm from the server logs.

What piece of this am I missing here?

bandejapaisa
  • 26,576
  • 13
  • 94
  • 112
  • After a lot of debugging, and creating sample apps and seeing that the default behaviour was in fact working. I've narrowed it down to the Authorization header that changes on every request. The server is returning a new token each request which I think dataTask/URLCache then treats this as a cache miss and hits the network again. – bandejapaisa Mar 30 '22 at 13:58

0 Answers0