ios - NSURLCache 对超过 max-age 的请求使用缓存
<p><p>我一直在努力想弄清楚 NSURLCache 发生了什么。</p>
<p>基本上,我要连接的服务器没有设置任何缓存控制 header ...因此,按照各种指南和苹果文档(即 <a href="https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/URLLoadingSystem/Concepts/CachePolicies.html" rel="noreferrer noopener nofollow">https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/URLLoadingSystem/Concepts/CachePolicies.html</a> ),我在 willCacheResponse 委托(delegate)中设置了自己的缓存控制 header ,然后将其返回完成处理程序中的修改响应。苹果文档和我读过的资源似乎表明这应该有效。但是我看到的是缓存的数据在它应该基于max-age过期后返回。似乎 max-age 被忽略了,并且 NSURLCache 正在使用另一种启发式方法来确定它是否应该从缓存中提取数据。</p>
<p>我设置了 max-age=60 缓存控制 header ,并使用 Charles 验证数据是从缓存中提取的,并且在 60 秒后很长时间没有发出任何网络请求。最终(似乎是不确定的)会发出一个新请求,该请求实际上会发送到服务器(通常在几个小时过去后,我会再次尝试该请求)。</p>
<p>这是代码,出于测试目的,我只是将 max-age 硬编码为 60 秒:</p>
<pre><code>func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, willCacheResponse proposedResponse: CachedURLResponse, completionHandler: @escaping (CachedURLResponse?) -> Void) {
var modifiedReponse: URLResponse? = nil
if let HTTPResponse = proposedResponse.response as? HTTPURLResponse {
if var newHeaders = HTTPResponse.allHeaderFields as? {
if newHeaders["Cache-Control"] == nil {
newHeaders["Cache-Control"] = "max-age=60"
}
modifiedReponse = HTTPURLResponse(url: HTTPResponse.url!, statusCode: HTTPResponse.statusCode, httpVersion: "HTTP/1.1", headerFields: newHeaders)
}
}
let response = modifiedReponse ?? proposedResponse.response
var newCachedResponse: CachedURLResponse? = nil
newCachedResponse = CachedURLResponse(response: response, data: proposedResponse.data, storagePolicy: proposedResponse.storagePolicy)
}
</code></pre>
<p>其中有一些可选检查,但我已确认我返回的 newCachedResponse 响应的缓存控制 header 设置为 max-age=60。我在这里做明显错误的事情吗?还是 NSURLCache 只是 F'd?</p></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>我知道这已经很晚了,但我认为您只需要将 newCachedResponse 传递回提供给您的完成处理程序闭包。</p>
<p>比如最后一行是:</p>
<pre><code>completionHandler(newCachedResponse)
</code></pre></p>
<p style="font-size: 20px;">关于ios - NSURLCache 对超过 max-age 的请求使用缓存,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/43075659/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/43075659/
</a>
</p>
页:
[1]