【问题标题】:Network requests timed out irregularly in Swift (using Alamofire)Swift 中的网络请求不规则超时(使用 Alamofire)
【发布时间】:2019-08-13 22:33:46
【问题描述】:

我们的一些请求很少和偶尔会遇到超时问题。很难重现,因为它只是突然发生并且在重试时(通过执行完全相同的操作重新发送请求,例如按下按钮),我们很可能会成功地得到响应。这发生在不同的设备上。

这里是我们的平台信息: XCode 10.1 斯威夫特 4.2 阿拉莫菲尔 4.8.1 PromiseKit 6.8.3

这是我们的请求示例之一:

public class NetworkingHelpers {
  // MARK: Singleton
  public static let shared = NetworkingHelpers()
  private let alamofireManager: SessionManager

  // MARK: Init
  private init() {    
    let configuration = URLSessionConfiguration.default
    configuration.timeoutIntervalForRequest = 30
    configuration.timeoutIntervalForResource = 30
    alamofireManager = Alamofire.SessionManager(configuration: configuration)
  }

  public func makePublicRequest<T: Decodable>(url: String, decodeAsType: T.Type, method: HTTPMethod = .get,
                                              params: [String: Any]? = nil) -> Promise<T> {
    return alamofireManager.request(url, method: method, parameters: params, encoding: JSONEncoding.default, headers: self.anonymousHeaders)
      .response(.promise)
      .recover(policy: .allErrorsExceptCancellation) { error -> Promise<(URLRequest, HTTPURLResponse, Data)> in
        // This is a error thrown by the alamofireManager, but not from the server
        // Most likely it is a timeout
        let e = error as NSError
        throw RequestErrorUtils.generateRequestError(e.code)
      }
      .then { (request, response, data) -> Promise<T> in
        // Process response
    }
  }

如果超时,Alamofire 会向我们抛出错误 -1001 代码,即 30 秒超时错误。这也意味着alamofireManager 已经处理了我们提出的请求。

这非常随机发生,正如我们所提到的,手动重试通常会成功。我们未能从服务器端捕获任何日志。我们对这个问题有一些假设。

  • iOS 存在错误,它会随机且偶尔丢失请求
  • Alamofire 有问题,它会随机且偶尔丢失请求
  • 我们的网络偶尔会随机掉线
  • 我们的服务器偶尔会随机响应失败

我们还将使用Netfox 来窥探来自我们设备的请求,以便我们可以缩小问题范围。

以前有没有人遇到过类似的问题? 谢谢!

【问题讨论】:

    标签: ios swift networking alamofire promisekit


    【解决方案1】:

    对于这样的问题,没有什么是决定性的,但对我来说,一直是网络问题。我没有使用过 Netfox,但查尔斯对此非常有帮助。我还使用 curl 等来获得第二意见(帮助您确定您是否/不疯狂等)。

    此时,由于您无法按照 Agan 的必读 book on debugging“刺激失败”,因此您需要更多信息。

    那么您最好的选择就是您所提到的 - 使用像 Charles 这样的代理来查看网络级别发生的事情(至少对于传出请求),并单独将日志记录添加到服务器。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-14
      • 2015-08-09
      • 2015-01-23
      • 2016-12-30
      • 2020-02-10
      • 2011-07-11
      相关资源
      最近更新 更多