我使用Alamofire
來處理對休息服務的請求。如果請求成功,則服務器返回JSON
,內容類型爲application/json
。但是如果請求失敗,服務器將返回一個簡單的String
。使用Alamofire處理未知內容類型的響應
所以,我不知道如何處理它與Alamofire
,因爲我不知道如何響應看起來像。我需要一個解決方案來處理不同的響應類型。
此代碼,我可以用它來處理一個成功的要求:
request(.POST, wholeUrl, parameters: parameters, encoding: .Custom(encodingClosure))
//.validate()
.responseJSON {
(request, response, data, error) -> Void in
//check if error is returned
if (error == nil) {
//this crashes if simple string is returned
JSONresponse = JSON(object: data!)
}
而且這個代碼,我可以用它來處理的失敗請求:
request(.POST, wholeUrl, parameters: parameters, encoding: .Custom(encodingClosure))
//.validate()
.responseString {
(request, response, data, error) -> Void in
//check if error is returned
if (error == nil) {
responseText = data!
}
我試過,但我怎麼能轉換'data'到'JSON(對象:數據) '或'字符串'?我必須分析響應數據才能執行代碼中的下一步。 – Karl 2015-03-02 19:45:53
您不必分析響應數據,只需檢查錯誤。我編輯了答案。 – sasquatch 2015-03-02 19:58:54
在成功案例中,我做了'response = JSON(object:data!)'。但是'response'在那之後是'null'。數據不爲空。 – Karl 2015-03-06 10:25:40