小编典典

Alamofire-NSURLCache无法正常工作?

swift

我将缓存设置如下

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

然后尝试检查缓存

var cachedResponse = NSURLCache.sharedURLCache().cachedResponseForRequest(urlRequest)

值是零

有什么想法吗?


阅读 321

收藏
2020-07-07

共1个答案

小编典典

我结束了手动添加Cache-Controlprivate我的请求的头,它现在的作品。甚至不需要手动检查缓存,Alamofire会为您完成

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)
2020-07-07