策略设置为ReloadIgnoringLocalAndRemot

策略设置为ReloadIgnoringLocalAndRemot

本文介绍了即使将缓存策略设置为ReloadIgnoringLocalAndRemoteCacheData,也可以从缓存加载Alamofire的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I set cache policy to request in Alamofire to ignore local cache.

然后,我通过网络连接加载了一个Viewcontroller,然后断开了网络连接,终止了该应用程序并再次运行它。

Then I load a viewcontroller with network connection, then I disconnect network connection, kill the app and run it again.

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

Now no network available error is not shown(ie alamofire doesnt create nserror object) created, instead app runs as if the request succeeded getting data from cache obviously.And the odd thing is the when I tried to inspect the cached data using

NSURLCache.sharedURLCache().cachedResponseForRequest(request)

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

nil is returned eventhough the data was from cache ..

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

The only way I could prevent cached responses is perform 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

    }

}
}

我想做什么是仅在网络连接不可用时才从缓存加载数据,例如受限的离线模式。

What I want to do is load data from cache only if network connection is not available, something like limited offline mode.How to do this?

推荐答案

I正在项目中使用这种方式,并且可以正常工作:

I'm using this way in a project and it's working:

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,也可以从缓存加载Alamofire的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 00:51