Alamofire.request(.GET, getUrl("mystuff")).validate()
- what is the use of the validate()
method? How can I use it to validate server connection issues?
Asked
Active
Viewed 1.1k times
10

Tamás Sengel
- 55,884
- 29
- 169
- 223

Ramesh Kumar
- 121
- 1
- 1
- 4
-
11Have you had the chance to read Alamofire documentation? https://github.com/Alamofire/Alamofire#automatic-validation – Lorenzo B Aug 30 '17 at 08:47
-
3I'm voting to close this question as off-topic because an answer can be found using Google or similar. In addition, the answer provided does not give an added value. It could be just a comment since the reply has been copied from the Alamofire documentation. – Lorenzo B Aug 30 '17 at 09:08
1 Answers
21
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
}

Tamás Sengel
- 55,884
- 29
- 169
- 223
-
I agree with you that SO can be used as a tool for clarifications. But, your answer does not provide an added value. It's just copied over from the documentation. If instead, you are able to argue something new and useful it could be helpful also for other people. – Lorenzo B Aug 30 '17 at 09:13
-
2
-
So what if it detects a 4xx/5xx error? Does it go into the `.failure` case, and with what kind of error message to expect (multilingual?) and how do we know which error code? – CyberMew Nov 13 '21 at 16:27