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.
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:
.validate()
and handle everything manually.validate()
to .validate(statusCode: yourRange)
for the range you want to allow and handle them manually.More info here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With