Alamofire returns .Success on error HTTP status codes

后端 未结 4 1115
北海茫月
北海茫月 2020-12-29 03:16

I have a pretty simple scenario that I\'m struggling with. I\'m using Alamofire to register a user on a rest API. The first call to register is successful and the user can l

4条回答
  •  情深已故
    2020-12-29 03:49

    From the Alamofire manual:

    Validation

    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.

    You can manually validate the status code using the validate method, again, from the manual:

    Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
         .validate(statusCode: 200..<300)
         .validate(contentType: ["application/json"])
         .response { response in
             print(response)
         }
    

    Or you can semi-automatically validate the status code and content-type using the validate with no arguments:

    Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
         .validate()
         .responseJSON { response in
             switch response.result {
             case .success:
                 print("Validation Successful")
             case .failure(let error):
                 print(error)
             }
         }
    

提交回复
热议问题