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

Mar*_*eon 8 swift alamofire

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

  1. 网络连接(主机关闭,无法到达主机)vs
  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??
        }
    }
Run Code Online (Sandbox Code Playgroud)

我们希望以不同方式处理每个案例.在后一种情况下,我们想要询问答复.(在前者我们没有,因为没有回应).

Mar*_*eon 4

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

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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

如果result.error它是类型,AFError您可以使用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
}
Run Code Online (Sandbox Code Playgroud)

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