2016-12-03 78 views
7

使用Alamofire 4/3斯威夫特你怎么能的请求之间进行区分失败是由于:Alamofire:网络错误与无效状态码?

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

我们希望以不同方式处理各种情况。在后一种情况下,我们想询问答复。 (在前者中,我们并不是没有回应)。

+0

马库斯嘿,什么是你为这最后的解决方案? –

回答

3

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

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 
} 

也许有一个更好的办法,但似乎工作...

1

自动校验应考虑内200状态码... 299(成功码)范围内,所以当你得到一个无效的服务器的HTTP响应代码5XX(499指Client Closed Request)你确定它不是由验证依赖。

关于statusCode,我的建议是遵循正确的新规则来获得它。如果你有一些问题需要检索,看看这个SO answer

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

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

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

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

您还可以找到这些细节在官方Alamofire 4 GitHub的page

1

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会告诉你什么是问题