1

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?

2 Answers2

1

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.

Rob
  • 415,655
  • 72
  • 787
  • 1,044
  • Thanks Rob. It works. I was about to manually place a check for status codes. I guess i will have to read more documentation. – Shubham1212 Jul 14 '20 at 06:43
0

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.

rptwsthi
  • 10,094
  • 10
  • 68
  • 109
  • 1
    Thanks for the reply rptwsthi. I see that all completed requests are treated as success by Alamofire. Rob's answer of placing a validate() worked perfectly – Shubham1212 Jul 14 '20 at 06:46
  • Yes 100%. Robs' anweser have this really great bit of advice. :-) – rptwsthi Jul 14 '20 at 06:50