Alamofire - NSURLCache不工作?

时间:2015-01-05 18:33:19

标签: swift nsurlcache alamofire

我将缓存设置如下

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)

值为零

有什么想法吗?

6 个答案:

答案 0 :(得分:18)

我能够通过将页面写入sharedURLCache来手动缓存页面,如下所示:

    Alamofire.request(req)
        .response {(request, res, data, error) in
            let cachedURLResponse = NSCachedURLResponse(response: res!, data: (data as NSData), userInfo: nil, storagePolicy: .Allowed)
            NSURLCache.sharedURLCache().storeCachedResponse(cachedURLResponse, forRequest: request)
        }

NSURLCache似乎尊重服务器发送的标头,即使您在代码中的其他地方配置了相反的内容。

例如,维基百科API发送

Cache-control: private, must-revalidate, max-age=0

转换为:必须在0秒后重新验证 所以NSURLCache说:“好的,我不会缓存任何东西。”

但是通过手动将响应保存到缓存,它可以正常工作。至少在iOS 8.2上。

对这一个几乎失去了理智。 :)

答案 1 :(得分:9)

我最终在我的请求标题中手动添加Cache-Control private,现在可以使用了。甚至不需要手动检查缓存,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)

答案 2 :(得分:2)

[解决NSURLcache到期的Swift解决方案]

我认为这里的主要问题是:ReturnCacheDataElseLoad

@arayax给了你一个可能解决的答案,但我的解决方案是这样的:

由于我正在使用Alamofire进行网络请求,因此我设置了我的配置:

  configuration.requestCachePolicy = .ReturnCacheDataElseLoad

当我提出请求时,我会检查互联网连接,如果确实如此,那么清除NSURLCache,这样就会强制Alamofire在服务器上发出请求而不是从缓存中发出请求:

    if Reachability.isConnectedToNetwork() == true {
        ConfigService.cache.removeAllCachedResponses()
    }

    ConfigService.manager?.request(.GET, ...

我希望这会有所帮助,也许对于NSURLCache的其他类型的问题:)

答案 3 :(得分:1)

对我来说,删除这一切后,它是 Pragma→no-cache

答案 4 :(得分:0)

这就是我如何使用Alamofire 4和swift 3(半完整功能作为参考)的缓存:

 func getTheList(courseId : String )->  Void{
        appConstants.sharedInstance.startLoading()
        let TheURL = DEFAULT_APP_URL + "api/getMyList?Id="+ID
        let urlString = NSURL(string: TheURL)
        var mutableURLRequest = URLRequest(url: urlString! as URL)
        mutableURLRequest.httpMethod = "GET"
        mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
        mutableURLRequest.cachePolicy = NSURLRequest.CachePolicy.returnCacheDataElseLoad


        Alamofire.request(mutableURLRequest)
            .responseJSON
           {.......

答案 5 :(得分:0)

我发现URLCache不能保存大于5%(1/20)容量的响应。

默认缓存有memoryCapacity = 512000,它不会保存到大于25600的内存响应。

作为解决方案扩展容量