OGeek|极客世界-中国程序员成长平台

标题: ios - NSURLCache 对超过 max-age 的请求使用缓存 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 19:21
标题: ios - NSURLCache 对超过 max-age 的请求使用缓存

我一直在努力想弄清楚 NSURLCache 发生了什么。

基本上,我要连接的服务器没有设置任何缓存控制 header ...因此,按照各种指南和苹果文档(即 https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/URLLoadingSystem/Concepts/CachePolicies.html ),我在 willCacheResponse 委托(delegate)中设置了自己的缓存控制 header ,然后将其返回完成处理程序中的修改响应。苹果文档和我读过的资源似乎表明这应该有效。但是我看到的是缓存的数据在它应该基于max-age过期后返回。似乎 max-age 被忽略了,并且 NSURLCache 正在使用另一种启发式方法来确定它是否应该从缓存中提取数据。

我设置了 max-age=60 缓存控制 header ,并使用 Charles 验证数据是从缓存中提取的,并且在 60 秒后很长时间没有发出任何网络请求。最终(似乎是不确定的)会发出一个新请求,该请求实际上会发送到服务器(通常在几个小时过去后,我会再次尝试该请求)。

这是代码,出于测试目的,我只是将 max-age 硬编码为 60 秒:

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? [String : String] {

            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)
}

其中有一些可选检查,但我已确认我返回的 newCachedResponse 响应的缓存控制 header 设置为 max-age=60。我在这里做明显错误的事情吗?还是 NSURLCache 只是 F'd?



Best Answer-推荐答案


我知道这已经很晚了,但我认为您只需要将 newCachedResponse 传递回提供给您的完成处理程序闭包。

比如最后一行是:

completionHandler(newCachedResponse)

关于ios - NSURLCache 对超过 max-age 的请求使用缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43075659/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4