Alamofire.request中validate()方法的用途是什么? [英] What is the use of the validate() method in Alamofire.request?

查看:321
本文介绍了Alamofire.request中validate()方法的用途是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Alamofire.request(.GET,getUrl( mystuff))。validate()- validate()的用途是什么方法?如何使用它来验证服务器连接问题?

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

推荐答案

作为 GitHub上的文档提及, validate() 不带参数,检查状态码是否为2xx,以及标题的可选的 Accept 部分是否与响应的 Content-键入

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.

示例:

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)
    }
}

您可以为自定义验证选项提供 statusCode contentType 参数

示例:

Alamofire.request("https://example.com/get")
    .validate(statusCode: 200..<300)
    .validate(contentType: ["application/json", "application/xml"])
    .responseData { response in
        [...]
}

如果要手动检查状态代码,可以使用 response.response?.statusCode 访问它。

If you want to check the status code manually, you can access it with response.response?.statusCode.

示例:

switch response.response?.statusCode {
case 200?: print("Success")
case 418?: print("I'm a teapot")
default: return
}

这篇关于Alamofire.request中validate()方法的用途是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆