【问题标题】:how to ignore cached response using Alamofire?如何使用 Alamofire 忽略缓存的响应?
【发布时间】:2020-01-06 06:26:24
【问题描述】:

在这样的配置下使用 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)

我需要忽略缓存的数据,并且使用第一个不起作用。

【问题讨论】:

  • @Rishab 他的解决方案对我不起作用。
  • 我不认为缓存是你真正的问题。我认为您应该研究为什么您的第一个代码返回 -999 错误。如果删除 timeoutIntervalForRequestrequestCachePolicy 会发生什么?

标签: ios swift alamofire urlsession


【解决方案1】:

不确定您为什么会收到此错误,但有多种方法可以解决此错误。

1.您可以将时间戳添加到您的 API url,这样您就永远不会得到缓存的响应。

extension Date {
    func toMillis() -> Int64! {
        return Int64(self.timeIntervalSince1970 * 1000)
    }
} 

let currentTimeStamp = Date().toMillis()!
let url = "https://example.com?timestamp=\(currentTimeStamp)"
  1. 你可以这样做:

    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 ...
    

拍摄from

【讨论】:

  • 抱歉格式化,代码没有正确格式化
  • 第二种方式,你能举个第一种方式的例子吗
  • 给我一分钟
  • 我的 api 不应该支持这样的参数吗?
【解决方案2】:

有很多方法可以做到这一点(示例使用 Alamofire 5):

使用ephemeralURLSessionConfiguration

let configuration = URLSessionConfiguration.ephemeral
configuration.headers = .default
let session = Session(configuration: configuration)

使用不带URLCache 实例的URLSessionConfiguration

let configuration = URLSessionConfiguration.af.default
configuration.urlCache = nil
let session = Session(configuration: configuration)

将已发布的URLRequestcachePolicy 设置为reloadIgnoringLocalCacheData,这应该会阻止存储其响应:

var request = URLRequest(...)
request.cachePolicy = .reloadIgnoringLocalCacheData
session.request(request).response...

使用 Alamofire 5 的 CachedResponseHandler API 来防止基于每个请求的缓存:

session.request(...).cacheResponse(using: ResponseCacher.doNotCache).response...

【讨论】:

    【解决方案3】:

    -> 您是否在再次请求之前尝试删除 cacheResponse? https://stackoverflow.com/a/47869125/9298652

    -> 或者尝试将 NSURLConnectionDelegate 的 willCacheResponse 方法设置为 nil 以防止响应缓存。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-08
      • 2023-03-13
      • 2021-09-22
      • 2019-04-30
      • 2020-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多