如何禁用Alamofire中的caching
当我用Alamofire发送一个GET请求两次时,我得到了同样的回应,但我期待着一个不同的回应。 我想知道是否是因为caching,如果是这样,我想知道如何禁用它。
迅速3,alamofire 4
我的解决scheme是:
为Alamofire创build扩展:
extension Alamofire.SessionManager{ @discardableResult open func requestWithoutCache( _ url: URLConvertible, method: HTTPMethod = .get, parameters: Parameters? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: HTTPHeaders? = nil)// also you can add URLRequest.CachePolicy here as parameter -> DataRequest { do { var urlRequest = try URLRequest(url: url, method: method, headers: headers) urlRequest.cachePolicy = .reloadIgnoringCacheData // <<== Cache disabled let encodedURLRequest = try encoding.encode(urlRequest, with: parameters) return request(encodedURLRequest) } catch { // TODO: find a better way to handle error print(error) return request(URLRequest(url: URL(string: "http://example.com/wrong_request")!)) } } }
并使用它:
Alamofire.SessionManager.default .requestWithoutCache("https://google.com/").response { response in print("Request: \(response.request)") print("Response: \(response.response)") print("Error: \(response.error)") }
你有几个select。
完全禁用URLCache
let manager: Manager = { let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() configuration.URLCache = nil return Manager(configuration: configuration) }()
configuration请求caching策略
let manager: Manager = { let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() configuration.requestCachePolicy = .ReloadIgnoringLocalCacheData return Manager(configuration: configuration) }()
这两种方法应该为你做的伎俩。 欲了解更多的信息,我build议阅读NSURLSessionConfiguration和NSURLCache的文档。 另一个很好的参考是关于NSURLCache的 NSHipster文章。
这是为我工作。
NSURLCache.sharedURLCache().removeAllCachedResponses()
Swift 3
URLCache.shared.removeAllCachedResponses()
如果你想使用共享的Alamofirepipe理器的另一个select是做到这一点:
Alamofire.Manager.sharedInstance.session.configuration.requestCachePolicy = .ReloadIgnoringLocalCacheData
之后,您可以使用Alamofire.request(.GET, urlString)....
与新的caching策略。
在Alamofire 4和Swift 3 :
// outside function, inside class var sessionManager: SessionManager! func someFunc() { let configuration = URLSessionConfiguration.default configuration.urlCache = nil let sessionManager = Alamofire.SessionManager(configuration: configuration) sessionManager.request("http://example.com/get").responseJSON { response in // ... } }
[这种方法不禁用caching,它只是确保caching的文件不被重用]
一个更简单的方法来通过一个特定的电话caching问题是只是在调用参数中添加一个随机数。
对于Swift 3,可以使用arc4random()
生成一个随机数。
func getImage(url: String, completion: @escaping (UIImage?) -> ()) { let urlRequest = URLRequest(url: URL(string: url)!) URLCache.shared.removeCachedResponse(for: urlRequest) //URLCache.shared.removeAllCachedResponses() Alamofire.request(url).responseData { (dataResponse) in guard let data = dataResponse.data else { return completion(nil) } completion(UIImage(data: data, scale:1)) } }