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

lau*_*man 13 caching ios swift alamofire

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

然后我加载一个带有网络连接的viewcontroller,然后我断开网络连接,杀死应用程序并再次运行它.

现在没有显示网络可用错误(即alamofire没有创建nserror对象),而app运行就像请求成功从缓存中获取数据一样明显.奇怪的是当我尝试使用高速缓存数据检查时

NSURLCache.sharedURLCache().cachedResponseForRequest(request)
Run Code Online (Sandbox Code Playgroud)

如果数据来自缓存,则返回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

    }

} 
}
Run Code Online (Sandbox Code Playgroud)

我想要做的只是在网络连接不可用的情况下从缓存加载数据,例如有限的离线模式.如何做到这一点?

Fáb*_*ata 12

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

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...
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你.


Ahm*_*tem 7

感谢@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 ...
Run Code Online (Sandbox Code Playgroud)


rob*_*nde 5

未实现ReloadIgnoringLocalAndRemoteCacheData。

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

http://nshipster.com/nsurlcache/

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