即使缓存策略设置为 ReloadIgnoringLocalAndRemoteCacheData,Alamofire 也会从缓存中加载

Alamofire loading from cache even when cache policy set to ReloadIgnoringLocalAndRemoteCacheData

我在 Alamofire 中将缓存策略设置为请求以忽略本地缓存。

然后我用网络连接加载 viewcontroller,然后我断开网络连接,关闭应用程序并再次 运行 它。

现在没有显示没有网络可用错误(即 alamofire 不创建 nserror 对象)创建,而不是应用程序 运行s 就好像请求成功从缓存中获取数据一样 obviously.And 奇怪的是当我尝试使用

检查缓存数据时
NSURLCache.sharedURLCache().cachedResponseForRequest(request)

即使数据来自缓存,也返回 nil ..

我可以阻止缓存响应的唯一方法是执行 NSURLCache.sharedURLCache().removeAllCachedResponses()

    let request = NSURLRequest(URL: NSURL(string: url)!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 100)

    Alamofire.manager.request(method, request, parameters:params)
    .responseJSON { (request, response, data, error) in
        if let anError = error {
            if anError.code == NSURLErrorNotConnectedToInternet {
                UIAlertView(title: "Alert", message: "No Network Connection Available", delegate: nil, cancelButtonTitle: "ok").show()
            }    

        } else if let data: AnyObject = data {
            println(NSURLCache.sharedURLCache().cachedResponseForRequest(request))
 //prints nil

    }

} 
}

我想做的是仅在网络连接不可用时才从缓存中加载数据,比如限制离线 mode.How 来做到这一点?

我在一个项目中使用了这种方式并且它正在工作:

let mutableURLRequest = NSMutableURLRequest(URL: SERVICEURL)
mutableURLRequest.HTTPMethod = "POST"

mutableURLRequest.HTTPBody = self.createJson()
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
mutableURLRequest.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData

request(mutableURLRequest).validate().responseJSON{ response in...

希望对您有所帮助。

ReloadIgnoringLocalAndRemoteCacheData 未实现。

https://developer.apple.com/reference/foundation/nsurlrequestcachepolicy/1408722-reloadignoringlocalandremotecach

http://nshipster.com/nsurlcache/

更新:从iOS13开始,实现了NSURLRequest.CachePolicy.reloadRevalidatingCacheData和NSURLRequest.CachePolicy.reloadIgnoringLocalAndRemoteCacheData。 https://developer.apple.com/documentation/ios_ipados_release_notes/ios_13_release_notes

感谢 @FábioSalata 我这样解决了我的问题。

 var req = URLRequest(url: URL(string: "<URL>")!)
 req.httpMethod = "GET"
 req.setValue("application/json", forHTTPHeaderField: "Content-Type")
 req.setValue("<Auth KEY>", forHTTPHeaderField:"Authorization" )
 req.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData

 Alamofire.request(req).validate().responseJSON { response in ...