问题
Alamofire.request(.GET, getUrl("mystuff")).validate()
- what is the use of the validate()
method? How can I use it to validate server connection issues?
回答1:
As the documentation on GitHub mentions, validate()
without parameters checks if the status code is 2xx and whether the optionally provided Accept
part of the header matches the response's Content-Type
.
Example:
Alamofire.request("https://example.com/get").validate().responseJSON { response in
switch response.result {
case .success:
print("Validation Successful")
case .failure(let error):
print(error.localizedDescription)
}
}
You can provide your custom validation options with statusCode
and contentType
parameters.
Example:
Alamofire.request("https://example.com/get")
.validate(statusCode: 200..<300)
.validate(contentType: ["application/json", "application/xml"])
.responseData { response in
[...]
}
If you want to check the status code manually, you can access it with response.response?.statusCode
.
Example:
switch response.response?.statusCode {
case 200?: print("Success")
case 418?: print("I'm a teapot")
default: return
}
来源:https://stackoverflow.com/questions/45955823/what-is-the-use-of-the-validate-method-in-alamofire-request