【问题标题】:Alamofire: Network error vs invalid status code?Alamofire:网络错误与无效状态码?
【发布时间】:2017-04-18 09:06:24
【问题描述】:

使用 Alamofire 4/Swift 3 如何区分因以下原因而失败的请求:

  1. 网络连接(主机关闭,无法访问主机)与
  2. 由于调用validate()导致Alamofire请求失败的服务器HTTP响应代码无效(即:499)?

代码:

    sessionManager.request(url, method: .post, parameters:dict, encoding: JSONEncoding.default)
        .validate() //Validate status code
        .responseData { response in

        if response.result.isFailure {
               //??NETWORK ERROR OR INVALID SERVER RESPONSE??
        }
    }

我们希望以不同的方式处理每种情况。在后一种情况下,我们要询问响应。 (在前者我们没有,因为没有回应)。

【问题讨论】:

  • 嘿马库斯,你的最终解决方案是什么?

标签: swift alamofire


【解决方案1】:

这是我们目前的工作解决方案:

sessionManager.request(url, method: .post, parameters:dict, encoding: JSONEncoding.default)
    .validate() //Validate status code
    .responseData { response in

    if response.result.isFailure {
        if let error = response.result.error as? AFError, error.responseCode == 499 {
            //INVALID SESSION RESPONSE
        } else {
            //NETWORK FAILURE
        }
    }
}

如果result.errorAFError 类型,您可以使用responseCode。来自AFError 来源 cmets:

/// Returns whether the `AFError` is a response validation error. When `true`, the `acceptableContentTypes`,
/// `responseContentType`, and `responseCode` properties will contain the associated values.
public var isResponseValidationError: Bool {
    if case .responseValidationFailed = self { return true }
    return false
}

也许有更好的方法(?),但这似乎有效......

【讨论】:

    【解决方案2】:

    Alamofire 可以告诉你请求的状态, 这段代码对我来说很好用:

    if let error = response.result.error as? NSError {
        print(error)//print the error description
        if (error.code == -1009){
                        print(error.code) // this will print -1009,somehow it means , there is no internet connection
                        self.errorCode = error.code
    
        }
          //check for other error.code    
    
    }else{
      //there is no problem
    }
    

    error.code 会告诉你问题出在哪里

    【讨论】:

      【解决方案3】:

      自动验证应考虑 200...299(成功代码)范围内的状态代码,因此当您收到无效的服务器 HTTP 响应代码 5xx(499 表示 @987654321 @) 你确定它不依赖于验证。

      关于statusCode,我的建议是遵循正确的新规则来获取它。如果您在检索它时遇到问题,请查看此 SO answer

      谈到网络可达性,你可以写:

      let manager = NetworkReachabilityManager(host: "www.apple.com")
      manager?.listener = { status in
          print("Network Status Changed: \(status)")
      }
      manager?.startListening()
      

      在使用网络可达性来确定下一步要做什么时,需要记住一些重要的事情。

      • 不要使用可达性来确定网络请求是否应该 发送。你应该总是发送它。
      • 恢复可达性后,使用事件重试失败的网络 要求。即使网络请求可能仍然失败,这是一个 重试它们的好时机。
      • 网络可达性状态可用于确定为什么 网络请求可能失败。如果网络请求失败,则 告诉用户网络请求因以下原因而失败更有用 离线而不是技术性错误,例如“请求 超时。”

      您也可以在官方的 Alamofire 4 GitHub page 中找到这些详细信息

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-05
        • 2016-04-16
        • 1970-01-01
        • 2015-03-22
        • 2020-07-09
        相关资源
        最近更新 更多