8

It is my first time for me to use Alamofire, and it got me really frustrated.

I'm using the following code to call a signup API on the backend API

Alamofire.request(.POST, "\(self.authBaseURL)/signup", parameters: params, headers: headers, encoding: .JSON)
            .validate(statusCode: 200..<300)
            .validate(contentType: ["application/json"])
            .responseJSON { response in
                switch response.result {
                case .Success(let JSON):
                    print("Success with JSON: \(JSON)")
                    success(updatedUser)
                case .Failure(let error):
                    print("Request failed with error: \(error)")
                    failure(error)
                }

        }

The problem is that the error object I'm getting in the .Failure function doesn't contain the server side message. I have tried to access the rest of the objects (request, response, data, result) I could not find my error message anywhere

I'm always getting the following error, no matter what the server message has to say. Request failed with error:

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

Is there is anything wrong I'm doing?

Swift 2.2, AlamoFire 3.3.0, Xcode 7.3

Alexey Pichukov
  • 3,377
  • 2
  • 19
  • 22
Joseph Wahba
  • 439
  • 2
  • 5
  • 16
  • So, instead of `.responseJSON` try `.responseString` and do the `print(response)` and see if you are getting something which isn't supposed to. Later, when you find the issue, switch back to `.responseJSON` – tush4r Mar 31 '16 at 10:55
  • Done that already, however the error I'm getting is still the same. The server is throwing the correct error message (I have created another client with AngularJS) but I'm still not able to get it in ios – Joseph Wahba Mar 31 '16 at 11:18
  • @JosephWahba were you able to solve your original problem? That is, getting at the Error Domain, Code, User Info data? I'm trying to do the same thing. Can you check out my question at http://stackoverflow.com/q/42591945/7029165 if you can help, please? – Daniel Mar 06 '17 at 17:55

3 Answers3

11

I managed to get it to work exactly the way I want is by dropping the status validation and check for the statusCode manually

Alamofire.request(.POST, "\(self.authBaseURL)/signup", parameters: params, headers: headers, encoding: .JSON)
            .validate(contentType: ["application/json"])
            .responseJSON { response in
                if response.response?.statusCode == 200 {
                    print("Success with JSON: \(response.result.value)")

                    success(updatedUser)
                }
                else {
                    let error = response.result.value as! NSDictionary
                    let errorMessage = error.objectForKey("message") as! String
                    print(errorMessage)
                    failure(errorMessage)
                }


        }
Joseph Wahba
  • 439
  • 2
  • 5
  • 16
  • 1
    I am not able to get server error log with 404 Status code, data field is always nil and getting this response [Result]: FAILURE: Error Domain=NSURLErrorDomain Code=-1015 "cannot decode raw data" – Rinkesh May 10 '16 at 06:11
3

This is how to get the error domain, code and user info with Alamofire 4 and Swift 3. User info contains the error strings.

Alamofire.request(.POST, "\(self.authBaseURL)/signup", parameters: params, headers: headers, encoding: .JSON)
            .validate(statusCode: 200..<300)
            .validate(contentType: ["application/json"])
            .responseJSON { response in
                switch response.result {
                case .Success(let JSON):
                    print("Success with JSON: \(JSON)")
                    success(updatedUser)
                case .Failure(let error):
                    let errorCode = error._code
                    let errorDomain = error._domain
                    let userInfo = error._userInfo
                    print("Request failed with error: \(error), code: \(errorCode), domain: \(errorDomain)")
                    failure(error)
                }

        }
SafeFastExpressive
  • 3,637
  • 2
  • 32
  • 39
2

updated for swift 3 :

Used below lines of code:-

    Alamofire.request(escapedString!, method: .get, encoding: JSONEncoding.default)
        .validate(contentType: ["application/json"])
        .responseJSON { response in
            if response.response?.statusCode == 200 {
                print("Success with JSON: \(String(describing: response.result.value))")

            }
            else {
                let error = (response.result.value  as? [[String : AnyObject]])
                print(error as Any)
            }
    } 
Kiran Jadhav
  • 3,209
  • 26
  • 29
  • Not only does this not work, but it will crash if result.value is nil, which it normally is for AlamoFire Result. – SafeFastExpressive Aug 29 '17 at 21:29
  • @Randy Hill, I updated above code.....now it's working fine...! please check again and let me know if you have any problem with it? – Kiran Jadhav Aug 30 '17 at 05:13
  • I removed my down vote because it won't crash now, and it's a reasonable example of using .responseJSON. But the question used validate(statusCode: 200..<300), which forces errors to be handled entirely differently. It provides a response.result that tells you if it's successful, and directly gives an error object for .failure. See my example. – SafeFastExpressive Sep 01 '17 at 16:15
  • @Randy Hill,,,, I will try to give you the best possible solution for your question??? Thanks for preferring above solution..! – Kiran Jadhav Sep 02 '17 at 04:58