Alamofire: There is no way of getting the response body

Created on 27 Sep 2015  路  10Comments  路  Source: Alamofire/Alamofire

When I try to get data using Alamofire and when error thrown from the server. I can get the statusCode from the response but there is no way of getting the response body.

support

Most helpful comment

Why not change Result.swift to return the value in the Failure case?

I need to use .validate(statusCode: 200..<300) and my server return a json with error messages. I just can't use that, because I just don't have the value.

Now, I need to take off the .validade and handle the status code manually.

/// Returns the associated value if the result is a success, 'nil' otherwise.
    public var value: Value? {
        switch self {
        case .Success(let value):
            return value
        case .Failure:
            return nil
        }
    }

All 10 comments

It depends on what version of Alamofire you are using, but you can always get the original server data in the event of an error if you are using either the Alamofire 2.x or 3.x releases.

Alamofire 2.x

Alamofire.request(.GET, "http://httpbin.org/get")
         .responseJSON { request, response, result in
             print(result)
             debugPrint(result)

             print(result.data) // original server data if .Failure case
         }

Alamofire 3.x

Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"])
         .responseJSON { response in
             print(response.request)  // original URL request
             print(response.response) // URL response
             print(response.data)     // server data
             print(response.result)   // result of response serialization

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

In my situation when I make the request through Postman it returns me the result as "412 Validation Failed". According to this example status code 412. I wanna retrieve the message(Validation Failed). I jusr Alamofire 2.* and the response is as follows:

{ URL: http://api.smartpricelk.com/api/Vehicle?vin=XXXXXXXXXXXXXX } { status code: 412, headers {n "Cache-Control" = "no-cache";n "Content-Length" = 28;n "Content-Type" = "text/plain; charset=utf-8";n Date = "Thu, 24 Sep 2015 18:15:13 GMT";n Expires = "-1";n Pragma = "no-cache";n Server = "Microsoft-IIS/8.5";n "X-AspNet-Version" = "4.0.30319";n "X-Powered-By" = "ASP.NET";n} }

It returns nil in data. Any idea on this.

You can print out the error in result. That will give you additional info.

Hi cnoon,

but it does not give the really important part like response string of server itself :) :(

"Access-Control-Allow-Origin" = "*";
"Cache-Control" = "no-cache";
"Content-Length" = 139;
"Content-Type" = "application/json; charset=utf-8";
Date = "Fri, 24 Jun 2016 15:35:32 GMT";
Expires = 0;
"Proxy-Connection" = Close;
Server = Apache;
"X-Powered-By" = "PHP/7.0.0";
"X-Status-Code" = 400;

} }
FAILURE: Error Domain=com.alamofire.error Code=-6003 "Response status code was unacceptable: 400" UserInfo={StatusCode=400, NSLocalizedFailureReason=Response status code was unacceptable: 400}

What i need is the error object son string server returned me which contains the actual error code like:

"{error : {code: 101, message: "invalid email format"}}"

I think i need to convert response.data to utf8 string and than convert it to json. right?

I am using SwiftyJSON for the moment, like :

JSON.init(data: response.data)

Why not change Result.swift to return the value in the Failure case?

I need to use .validate(statusCode: 200..<300) and my server return a json with error messages. I just can't use that, because I just don't have the value.

Now, I need to take off the .validade and handle the status code manually.

/// Returns the associated value if the result is a success, 'nil' otherwise.
    public var value: Value? {
        switch self {
        case .Success(let value):
            return value
        case .Failure:
            return nil
        }
    }

For someone who wants to check response message, you need to convert Data to String to print it out in Xcode console.

The response message is in the response.data which is in Data type

debugPrint(String(data: response.data!, encoding: String.Encoding.utf8)!)

You can get a String from Data more easily: String(decoding: data, as: UTF8.self). But really, if you debugPrint the entire response the request and response body data will be printed for you in Alamofire 5.

I get response body error code and error message by using the following code:

var JSON: [String: Any]?

failure: { (response: DataResponse, error : Error) in
do {
JSON = try JSONSerialization.jsonObject(with: response.data!, options: []) as? [String: Any]
let code = JSON!["code"] as? Int
let message = JSON!["message"] as? String
print(code)
print(message)
} catch {
// Your handling code
}
}

Was this page helpful?
0 / 5 - 0 ratings

Related issues

lvandal picture lvandal  路  3Comments

matthijsotterloo picture matthijsotterloo  路  3Comments

Footjy picture Footjy  路  3Comments

shivang2902 picture shivang2902  路  3Comments

Tulleb picture Tulleb  路  3Comments