我将缓存设置如下
var cacheSizeMemory = 20 * 1024 * 1024 var cacheSizeDisk = 100 * 1024 * 1024 var sharedCache = NSURLCache(memoryCapacity: cacheSizeMemory, diskCapacity: cacheSizeDisk, diskPath: "SOME_PATH") NSURLCache.setSharedURLCache(sharedCache)
使用缓存策略创建请求
var request = NSMutableURLRequest(URL: NSURL(string: "\(baseUrl!)\(path)")!, cachePolicy: .ReturnCacheDataElseLoad, timeoutInterval: timeout)
发出请求并获得以下答复 Cache-Control private, max-age=60
Cache-Control
private, max-age=60
然后尝试检查缓存
var cachedResponse = NSURLCache.sharedURLCache().cachedResponseForRequest(urlRequest)
值是零
有什么想法吗?
我结束了手动添加Cache-Control为private我的请求的头,它现在的作品。甚至不需要手动检查缓存,Alamofire会为您完成
private
let cachePolicy: NSURLRequestCachePolicy = isReachable() ? .ReloadIgnoringLocalCacheData : .ReturnCacheDataElseLoad var request = NSMutableURLRequest(URL: NSURL(string: "\(baseUrl!)\(path)")!, cachePolicy: cachePolicy, timeoutInterval: timeout) request.addValue("private", forHTTPHeaderField: "Cache-Control") var alamoRequest = Manager.sharedInstance.request(urlRequest)