4

I'm new to iOS and Swift and I'm trying to use AlamoFire 3.4.0 to make a web request. When my request is successful, everything works fine. However, if my request fails, the server will return a status code of 300 or greater and some JSON in the response body with more information about why the request failed. For example, the API I'm talking to requires each request to be authenticated. If the authentication fails for some reason, I'll get back 401 and the JSON in the response body will be:

{"developerMessage" : "Request failed because signature was incorrect."}

My code to make this request looks like this:

let headers = [
   "X-Auth-Signature" : signature
]

Alamofire.request(.GET, "https://server.com/get", headers: headers)
         .validate()
         .responseJSON { response in
             switch response.result {
             case .Success(let json)
                // process JSON response here
             case .Failure(let error)
                print("Request failed with error: \(error)")
                // how can I access the JSON in the response body from here?
             }
         }

It's my understanding that the call to .validate() will verify that the status code is 200 - 299 and everything else outside that range will result in the .Failure case. Assuming that that is correct, when I get back 401, how can I access the JSON in the response body from inside my failure handler? Thanks very much!

bmt22033
  • 6,880
  • 14
  • 69
  • 98

1 Answers1

0
case .Failure(let error)    
    if let JSON = response.result.value {
        print("JSON: \(JSON)")
    }

should do the trick

Dominik Vincenz
  • 445
  • 3
  • 10