[英]how to ignore cached response using Alamofire?
將 Alamofire 與這樣的配置一起使用,導致錯誤 -999 請求被取消
let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForRequest = 20
configuration.requestCachePolicy = .reloadIgnoringLocalCacheData
var sessionManager = Alamofire.SessionManager(configuration: configuration)
sessionManager.request(url,
method: methodType,
parameters: resource.parameters,
headers: resource.headers)
但是,當我像這樣使用它時,它直接工作正常,但它會緩存響應..
Alamofire.request(url,
method: methodType,
parameters: resource.parameters,
headers: resource.headers)
我需要忽略緩存的數據,使用第一個不起作用。
不確定為什么會出現此錯誤,但有多種方法可以解決此錯誤。
1.您可以在您的 API url 中添加時間戳,這樣您就永遠不會得到緩存響應。
extension Date {
func toMillis() -> Int64! {
return Int64(self.timeIntervalSince1970 * 1000)
}
}
let currentTimeStamp = Date().toMillis()!
let url = "https://example.com?timestamp=\(currentTimeStamp)"
您可以執行以下操作:
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 ...
采取從
有很多方法可以實現這一點(示例使用 Alamofire 5):
使用ephemeral
URLSessionConfiguration
:
let configuration = URLSessionConfiguration.ephemeral
configuration.headers = .default
let session = Session(configuration: configuration)
使用URLSessionConfiguration
沒有一個URLCache
的實例:
let configuration = URLSessionConfiguration.af.default
configuration.urlCache = nil
let session = Session(configuration: configuration)
將發出的URLRequest
的cachePolicy
為reloadIgnoringLocalCacheData
,這應該會阻止其響應的存儲:
var request = URLRequest(...)
request.cachePolicy = .reloadIgnoringLocalCacheData
session.request(request).response...
使用 Alamofire 5 的CachedResponseHandler
API 來防止基於每個請求進行緩存:
session.request(...).cacheResponse(using: ResponseCacher.doNotCache).response...
-> 您是否嘗試在再次請求之前刪除 cacheResponse? https://stackoverflow.com/a/47869125/9298652
-> 或者嘗試將 NSURLConnectionDelegate 的 willCacheResponse 方法設置為 nil 以防止緩存響應。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.