Stevik
Stevik

Reputation: 1152

iOS Swift 2 - Alamofire print response value when Failure

I'm using Alamofire for my http requests but I'm not able to get error message from requests that don't pass validation

Alamofire.request(method, url, headers: headers, parameters: parameters, encoding: encoding)
            .validate(statusCode: 200..<300)
            .responseJSON { response in

                switch response.result {
                case .Success:
                    // response.result.value returns JSON

                case .Failure(let error):
                    // response.result.value returns nil
                }
        }

How can I get data (JSON) if I get error code 400 and others. The API is sending the data in body even if the request was not successful.

Upvotes: 3

Views: 1224

Answers (2)

Yuki Sato
Yuki Sato

Reputation: 31

As Following SaiCYLi, Only way to get response data is avoid using validate.
See Result.swift in Alamofire.
There is blocker.

public var value: Value? {
    switch self {
    case .Success(let value):
        return value
    case .Failure:
        return nil
    }
}

I wanted comment to you instead of answering. But I have reputation less than 50. Sorry.

Upvotes: 3

taipingeric
taipingeric

Reputation: 715

just delete your validation of status code

Code:

Alamofire.request(method, url, headers: headers, parameters: parameters, encoding: encoding)
      .responseJSON { 
      response in
            let statusCode = response.response.statusCode
            switch statusCode {
            case 200..<300:
                // Success
            case 404:
                // not found
            default: 
                // something else
            }
    }

Upvotes: 2

Related Questions