如何在 Alamofire 中禁用缓存 [英] How to disable caching in Alamofire
本文介绍了如何在 Alamofire 中禁用缓存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我使用 Alamofire 发送两次 GET 请求时,我得到相同的响应,但我期待不同的响应.我想知道是不是因为缓存,如果是,我想知道如何禁用它.
When I send a GET request twice with Alamofire I get the same response but I'm expecting a different one. I was wondering if it was because of the cache, and if so I'd like to know how to disable it.
推荐答案
swift 3, alamofire 4
swift 3, alamofire 4
我的解决方案是:
为 Alamofire 创建扩展:
creating extension for Alamofire:
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)")
}
这篇关于如何在 Alamofire 中禁用缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文