Greetings,
I would like to understand this URLCache behavior for two different requests to the same end point but with a different header value. Here is a code with comment explaining the behavior.
// Create a request to for a url.
let url = URL(string: "https://<my url>?f=json")!
var request = URLRequest(url: url)
// Set custom header with a value.
request.setValue("myvalue", forHTTPHeaderField: "CustomField")
// Send request to get the response.
let (data, response) = try await URLSession.shared.data(for: request)
print("data: \(String(describing: String(data: data, encoding: .utf8)))")
print("response: \(response)")
// Create second request to the same url but with different value of custom header field.
var request2 = URLRequest(url: url)
request2.setValue("newvalue", forHTTPHeaderField: "CustomField")
// Check the URL cache for second request and it returns the response
// of the first request even though the second request has different header value.
let cachedResponse = URLCache.shared.cachedResponse(for: request2)
print("cachedResponse: \(cachedResponse?.response)")
Is this a bug in URLCache that request headers are not matched while returning the response? Is this an expected behavior? If yes, why?
has this ever been resolved?
I’m not sure we’d considered this a bug to be resolved. As my colleague mentioned above:
the three things that affect the cache lookup are base URL, caching headers for a previous response, and request bodies.
Custom headers aren’t considered significant by the cache.
If you’d like to see that change you are free to file a bug explaining your rationale. Ideally that’d include a reference to the RFC text that supports your position.
And if you do file a bug, please post your bug number, just for the record.
Alternatively, you can do your own caching. URLCache
is very general purpose, with the overall goal of supporting web browser-y semantics. You can often do a lot better by creating a cache whose semantics match your specific requirements.
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"