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

久未见 提交于 2019-12-22 10:39:51

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!