URLSession 和 URLCache 未按预期工作
对于始终如一的GET请求(它也有一个查询参数),我正在返回此响应标头的响应中。
Cache-Control: max-age=3600, private
我正在用这种配置创建一个urlsession。基本上,确保我的缓存很大。在应用程序的整个生命中,所有要求都持续存在。
var configuration = URLSessionConfiguration.default
let cache = URLCache(memoryCapacity: 500_000_000, diskCapacity: 1_000_000_000)
configuration.urlCache = cache
configuration.requestCachePolicy = .useProtocolCachePolicy
我使用完整处理程序创建数据任务:
let task = session.dataTask(with: request) { data, response, error in
//... my response handling code here
}
task.resume()
我在做任何复杂或不寻常的事情。我现在试图通过缓存策略优化一些呼叫。
因此,我有2个问题:
具有无缓存策略的请求仍将保存到Urlcache中。我通过研究
urlcache
来确认。当响应明确指出无缓存策略时,为什么要缓存它们,并且我告诉会议使用协议策略。在我想使用缓存的请求中,当我致电session.datatask在随后的时间时,它永远不会从缓存中获取。它总是再次击中服务器 - 我可以从服务器日志中确认。
我在这里错过了什么部分?
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:
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.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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论