使用 Alamofire 4/Swift 3 如何区分由于以下原因而失败的请求:
- 网络连接(主机宕机,无法连接到主机)对比
- 无效的服务器 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.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
}
也许有更好的方法(?)但这似乎有效...
关于swift - Alamofire:网络错误与无效状态代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40949407/