Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of the validate() method in Alamofire.request? [closed]

Alamofire.request(.GET, getUrl("mystuff")).validate() - what is the use of the validate() method? How can I use it to validate server connection issues?

like image 345
Ramesh Kumar Avatar asked Aug 30 '17 08:08

Ramesh Kumar


People also ask

What is Alamofire used for?

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”).

Does Alamofire support async await?

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.

Is Alamofire asynchronous?

Networking in Alamofire is done asynchronously.


1 Answers

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
}
like image 167
Tamás Sengel Avatar answered Sep 20 '22 16:09

Tamás Sengel