Alamofire.request(.GET, getUrl("mystuff")).validate()
- what is the use of the validate()
method? How can I use it to validate server connection issues?
Alamofire is a networking library written in Swift. You use it to make HTTP(S) requests on iOS, macOS and other Apple platforms. For example, to post data to a web-based REST API or to download an image from a webserver. Alamofire has a convenient API built on top of URLSession (“URL Loading System”).
You can now also await all of the various asynchronous bits of state simultaneously. The newly added static accessors allow for much more fluent composition of Alamofire's various protocol types.
Networking in Alamofire is done asynchronously.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With