URLSession 和 URLCache 未按预期工作

发布于 2025-01-17 19:40:18 字数 928 浏览 0 评论 0原文

对于始终如一的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个问题:

  1. 具有无缓存策略的请求仍将保存到Urlcache中。我通过研究urlcache来确认。当响应明确指出无缓存策略时,为什么要缓存它们,并且我告诉会议使用协议策略。

  2. 在我想使用缓存的请求中,当我致电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:

  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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文