当我直接查询NSURLCache
时,我能够看到缓存响应,但当我通过NSURLSession:dataTaskWithRequest
请求相同资源时,它始终查询服务器,并且从未给我缓存响应,即使禁用了Internet也是如此。NSURLSession不使用缓存响应
我application:didFinishLaunchingWithOptions
配置NSURLCache
这样的:
let URLCache = NSURLCache(memoryCapacity: 20 * 1024 * 1024,
diskCapacity: 80 * 1024 * 1024, diskPath: nil)
NSURLCache.setSharedURLCache(URLCache)
然后我使用此代码来检查缓存并获取响应:
print("cached response is \(NSURLCache.sharedURLCache().cachedResponseForRequest(request)?.response)")
NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
print("nsurlsession response \(response)")
}.resume()
我调试输出的结果是:
cached response is Optional(<NSHTTPURLResponse: 0x7f809d0ddfe0> { URL: https://api.test.com/stuff } { status code: 200, headers {
"Cache-Control" = "public, s-maxage=600";
Connection = "keep-alive";
"Content-Type" = "application/json";
Date = "Tue, 06 Sep 2016 23:41:24 GMT";
Etag = "\"4800a836fee27c56a3cce1f0f2bddaefa5a7785b\"";
Server = "nginx/1.11.3";
"Transfer-Encoding" = Identity;
"X-RateLimit-Limit" = 60;
"X-RateLimit-Remaining" = 2; } })
nsurlsession response Optional(<NSHTTPURLResponse: 0x7f809d202e50> { URL: https://api.test.com/stuff } { status code: 200, headers {
"Cache-Control" = "public, s-maxage=600";
Connection = "keep-alive";
"Content-Type" = "application/json";
Date = "Tue, 06 Sep 2016 23:51:52 GMT";
Etag = "\"4800a836fee27c56a3cce1f0f2bddaefa5a7785b\"";
Server = "nginx/1.11.3";
"Transfer-Encoding" = Identity;
"X-RateLimit-Limit" = 60;
"X-RateLimit-Remaining" = 52; } })
正如你所看到的,来自t的Cache-Control头他的服务器设置为允许缓存。我没有对我的请求做任何特别的处理,只是通过URL创建一个默认的NSURLRequest
。每次我触发请求时,新的响应都会被缓存,但在后续请求中永远不会检索到。
NSURLSession
是否有任何理由不使用存储在NSURLCache
中的响应?我需要做些什么才能告诉NSURLSession
实际查找缓存中的请求?
谢谢你,这是*非常*有帮助。作为一名前端工程师,我很难找出所有可能发生网络问题的地方。我尝试打击TVDB网址以消除客户端配置的问题,并且缓存适用于此,所以我怀疑这个问题与ETag重新验证有关。 – NewShelbyWoo
发现服务器在ETag验证期间没有发送304s。与查尔斯代理验证,并得到修复。我没有意识到客户会在响应失效之前尝试验证。 – NewShelbyWoo
整洁。很高兴这有帮助。 – dgatwood