Shubham1212
Shubham1212

Reputation: 33

Incorrect response from Alamofire?

I am making a request to a server using Alamofire. Here is how i am doing it:

Alamofire.request(url, method: .post, parameters: [:] ,encoding: JSONEncoding.default).responseJSON { response in

            print("response=\(response)")
            print("Response=:\((response.response?.statusCode)!)")
            switch response.result{
            case .success :
                let passList = AuthenticateSuccess(nibName: "AuthenticateSuccess", bundle: nil)
                self.navigationController?.pushViewController(passList, animated: true)
                print("connected")
            case .failure(let error):
                self.showAlertTost("", msg: "Authentication Failed. Authenticate again!", Controller: self)
                

            }
        }

This is what prints:

response=SUCCESS: {
    message = "Access denied.";
}
Response=:401
connected

I want to know that if 401 is error why is success block being executed? Is failure case in Alamofire handled differently?

Upvotes: 1

Views: 359

Answers (2)

rptwsthi
rptwsthi

Reputation: 10172

response.success depicts that the server has returned the response. Whereas 401 is something that is related to the REST response which your backend system generated. Hence add the check to response code after verifying that you have received the response to provide better information to the end-user.

Upvotes: 0

Rob
Rob

Reputation: 437412

As the documentation says:

By default, Alamofire treats any completed request to be successful, regardless of the content of the response. Calling validate() before a response handler causes an error to be generated if the response had an unacceptable status code or MIME type.

E.g.

Alamofire.request(url, method: .post, encoding: JSONEncoding.default)
    .validate()
    .responseJSON { response in
        ...
}

With validate, non 2xx responses will now be treated as errors.

Upvotes: 1

Related Questions