2015-12-07 3 views
5

Il mio server (CakePHP) risponde in questo modo:Get messaggio di risposta del server da errori

$this->response->statusCode('400'); 
$this->response->type('json'); 
$this->response->body(json_encode(array('message' => 'Bookmark already exists'))); 

L'output postino sembra che quello che ci si aspetta:

{ "messaggio": "Segnalibro esiste già" }

il problema è che non riesco a trovare un modo per accedere a questo messaggio dal gestore di fallimento (Alamofire 3.1.3 + SwiftyJSON 2.3.2)

Alamofire.request(.POST... 
.validate() 
.responseJSON { response in 

switch response.result { 

case .Success(_):       
// All good 

case .Failure(let error): 
// Status code 400     
print(response.request) // original URL request 
print(response.response) // URL response 
print(response.data)  // server data 
print(response.result) 

Non riesco a trovare un modo per trasmettere response.data a JSON come un I semplicemente ottenere nil e il risultato restituisce solo FAILURE.

C'è un modo per accedere a questo messaggio del server dal gestore degli errori?

+0

aggiungerti codice swift –

risposta

3

Ho utilizzato le seguenti righe per leggere il corpo della risposta da una richiesta Alamofire.

Alamofire.request(.POST, serveraddress, headers: headers, encoding: .JSON) 
     .response{ request, response, data, error in 
      let responseData = String(data: data!, encoding: NSUTF8StringEncoding) 
      print(responseData) 


    } 

Con questo corpo posso ottenere il mio errore di risposta del server personalizzato.

migliori saluti

11

I dati non vengono analizzati nel caso .Failure per il Alamofire 3.0 migration guide. Tuttavia, i dati del server sono ancora disponibili in response.data e possono essere analizzati.

seguito dovrebbe funzionare per analizzare manualmente:

Alamofire.request(.POST, "https://example.com/create", parameters: ["foo": "bar"]) 
    .validate() 
    .responseJSON { response in 
    switch response.result { 
    case .Success: 
     print("Validation Successful") 
    case .Failure(_): 
      var errorMessage = "General error message" 

      if let data = response.data { 
      let responseJSON = JSON(data: data) 

      if let message: String = responseJSON["message"].stringValue { 
       if !message.isEmpty { 
       errorMessage = message 
       } 
      } 
      } 

      print(errorMessage) //Contains General error message or specific. 
    } 
    } 
} 

Questo utilizza SwiftyJSON che fornisce la struct JSON per convertire NSData. L'analisi da NSData a JSON può essere eseguita senza SwiftyJSON, ha risposto here.

Un'altra opzione di pulizia potrebbe essere quella di scrivere un Custom Response Serializer.

+0

Grazie, davvero salvato il mio giorno :) –

4

Metodo con il router e non SwiftyJSON:

Alamofire.request(APIRouter.Register(params: params)).validate().responseJSON { response in 
    switch response.result { 
     case .Success(let json): 
      let message = json["clientMessage"] as? String 
      completion(.Success(message ?? "Success")) 
     case .Failure(let error): 
      var errorString: String? 

      if let data = response.data { 
       if let json = try? NSJSONSerialization.JSONObjectWithData(data, options: []) as! [String: String] { 
        errorString = json["error"] 
       } 
      } 

      completion(.Error(errorString ?? error.localizedDescription)) 
     } 
    }