Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting response data from Alamofire error

I've been using Alamofire in one of my iOS projects, but recently when upgrading to Alamofire 3.0 the format changed slightly for returning results. In my case I want to call a login API and have it return the result. There are a couple errors that could happen, so I always return in the API result what the problem is, so I would like my code to go into a failure block if the response is a 400 and then include the message from my API as part of the error, but I can not seem so get the response data from the request when the result is a failure.

Here's my code:

Alamofire.request(
        method,
        Constants.baseURL + route,
        parameters: fullParameters)
        .validate()
        .responseJSON { response in
            let json = JSON(response.result.value!)
            switch response.result {
            case .Success:
                completion?(json["data"])
            case .Failure(let errorData):
                failure?(errorData, json["errmsg"])
            }
    }

What is happening in this, is that when the response is a failure, it breaks because response.result.value is nil, but I would like it to be the JSON returned from the API no matter what. When the response is a success on the other hand it works perfectly.

like image 240
Henry Avatar asked Feb 17 '16 20:02

Henry


1 Answers

Since you're calling validate() Alamofire is automatically validating status code from 200...299.

If you don't want Alamofire to validate your status code, but you want to do it yourself manually you have two options:

  • Remove .validate() and handle everything manually.
  • Change validate() to .validate(statusCode: yourRange) for the range you want to allow and handle them manually.

More info here.

like image 53
fdiaz Avatar answered Oct 14 '22 05:10

fdiaz