2015-03-02 75 views
0

我使用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! 
       } 

回答

1

我已經解決了我的問題:

request(.POST, wholeUrl, parameters: parameters, encoding: .Custom(encodingClosure)) 
    .validate() 
.response { 
    (request, response, data, error) -> Void in 

     //check if error is returned 
     if (error == nil) { 
      var serializationError: NSError? 
      let json: AnyObject? = NSJSONSerialization.JSONObjectWithData(data! as! NSData, options: NSJSONReadingOptions.AllowFragments, error: &serializationError) 

      JSONresponse = JSON(object: json!) 
     } 
     else { 
      //this is the failure case, so its a String 
     } 
} 
2

不要指定響應類型,並且不要評論出.validate()。 檢查錯誤,然後進行相應處理

request(.POST, wholeUrl, parameters: parameters, encoding: .Custom(encodingClosure)) 
     .validate() 
    .response { 
     (request, response, data, error) -> Void in 

      //check if error is returned 
      if (error == nil) { 
       //this is the success case, so you know its JSON 
       //response = JSON(object: data!) 
      } 
      else { 
       //this is the failure case, so its a String 
      } 
    } 
+0

我試過,但我怎麼能轉換'data'到'JSON(對象:數據) '或'字符串'?我必須分析響應數據才能執行代碼中的下一步。 – Karl 2015-03-02 19:45:53

+0

您不必分析響應數據,只需檢查錯誤。我編輯了答案。 – sasquatch 2015-03-02 19:58:54

+0

在成功案例中,我做了'response = JSON(object:data!)'。但是'response'在那之後是'null'。數據不爲空。 – Karl 2015-03-06 10:25:40

相關問題