Alamofire 的响应不正确?

Incorrect response from Alamofire?

我正在使用 Alamofire 向服务器发出请求。这是我的做法:

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)
                

            }
        }

这是打印的内容:

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

我想知道,如果 401 是错误,为什么会执行成功块? Alamofire 中的失败案例处理方式不同吗?

正如the documentation所说:

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.

例如

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

使用 validate,非 2xx 响应现在将被视为错误。

response.success表示服务器已返回响应。而 401 是与后端系统生成的 REST 响应相关的内容。因此,在验证您已收到响应后添加对响应代码的检查,以向最终用户提供更好的信息。