2016-12-03 34 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會告訴你什麼是問題