我正在使用Xcode 6.1(6A1030),iOS7和iOS8模拟器。
NSURLCache似乎没有缓存任何内容。 我使用“Cache-Control”标头。我的服务器返回带有'max-age = 6000'的Cache-Control标头。
在此示例中,我篡改了Google的请求,该请求也未缓存:
的AppDelegate:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
var URLCache = NSURLCache(memoryCapacity: 500 * 1024 * 1024, diskCapacity: 500 * 1024 * 1024, diskPath: "bla")
NSURLCache.setSharedURLCache(URLCache)
sleep(1)
return true
}
然后我开始连接:
let urlPath: String = "http://www.google.com"
var url: NSURL = NSURL(string: urlPath)!
var request: NSURLRequest = NSURLRequest(URL: url, cachePolicy: NSURLRequestCachePolicy.ReturnCacheDataElseLoad, timeoutInterval: 5000)
var cachedURLResponse = NSURLCache.sharedURLCache().cachedResponseForRequest(request)
// cachedURLResponse is always nil
var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: true)!
connection.start()
在缓存响应之前,我添加了Cache-Control标头:
func connection(connection: NSURLConnection, willCacheResponse cachedResponse: NSCachedURLResponse) -> NSCachedURLResponse? {
var HTTPResponse = cachedResponse.response as NSHTTPURLResponse
var modifiedHeaders = NSMutableDictionary(dictionary: HTTPResponse.allHeaderFields)
modifiedHeaders["Cache-Control"] = "max-age=6000"
modifiedHeaders.removeObjectForKey("Expires")
var modifiedResponse = NSHTTPURLResponse(URL: HTTPResponse.URL!, statusCode: HTTPResponse.statusCode, HTTPVersion: "HTTP/1.1", headerFields: modifiedHeaders)
return NSCachedURLResponse(response: modifiedResponse!, data: cachedResponse.data, userInfo: cachedResponse.userInfo, storagePolicy: cachedResponse.storagePolicy)
}
修改后的响应如下所示:
{URL:http://www.google.com/?gfe_rd=cr&ei=MSBGVKe7AeeI8QepoYGgCg} {状态代码:200,headers { “Alternate-Protocol”=“80:quic,p = 0.01”; “Cache-Control”=“max-age = 6000”; “Content-Type”=“text / html; charset = windows-1255”; 日期=“星期二,2014年10月21日08:58:25 GMT”; 服务器= gws; “转移编码”=身份; “X-Frame-Options”= SAMEORIGIN; “X-XSS-Protection”=“1; mode = block”; }}
然而,'cachedResponseForRequest'每次都返回nil,每次都会发送一个新的服务器请求。
我做错了吗? 非常感谢你的帮助!