swift - Alamofire:网络错误与无效状态代码?

标签 swift alamofire

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

  1. 网络连接(主机宕机,无法连接到主机)对比
  2. 无效的服务器 HTTP 响应代码(即:499)导致 Alamofire 请求因调用 validate() 而失败?

代码:

    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??
        }
    }

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

最佳答案

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

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 来源评论:

/// 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
}

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

关于swift - Alamofire:网络错误与无效状态代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40949407/

相关文章:

swift - Alamofire 公钥固定不验证其他 url

swift - 如何使用 bezierPathWithCGPath Swift

ios - 恢复应用程序时重新加载 ViewController

ios - Alamofire GET If-None-Match 由于某种原因不起作用

swift - 使用 ObjectMapper 映射 JSON 对象的通用函数

ios - 快速启用/禁用开始和暂停按钮

ios - Swift iOS 13,使用移动网络(4g/3g)时未获取 APNS 设备 token

swift - 如何在 Alamofire Swift 中调用具有 get api 等参数的 post API?

json - "let JSON"在 Alamofire/Swift 中如何工作

arrays - 如何在嵌套的 JSON 值上使用 SwiftyJSON