Swift Alamofire:如何获取 HTTP 响应状态代码 [英] Swift Alamofire: How to get the HTTP response status code

查看:37
本文介绍了Swift Alamofire:如何获取 HTTP 响应状态代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检索请求失败的 HTTP 响应状态代码(例如 400、401、403、503 等)(最好也是成功的).在此代码中,我使用 HTTP Basic 执行用户身份验证,并希望能够在用户输入错误密码时向用户发送身份验证失败的消息.

I would like to retrieve the HTTP response status code (e.g. 400, 401, 403, 503, etc) for request failures (and ideally for successes too). In this code, I am performing user authentication with HTTP Basic and want to be able to message the user that authentication failed when the user mistypes their password.

Alamofire.request(.GET, "https://host.com/a/path").authenticate(user: "user", password: "typo")
    .responseString { (req, res, data, error) in
        if error != nil {
            println("STRING Error:: error:(error)")
            println("  req:(req)")
            println("  res:(res)")
            println("  data:(data)")
            return
        }
        println("SUCCESS for String")
}
    .responseJSON { (req, res, data, error) in
        if error != nil {
            println("JSON Error:: error:(error)")
            println("  req:(req)")
            println("  res:(res)")
            println("  data:(data)")
            return
        }
        println("SUCCESS for JSON")
}

不幸的是,产生的错误似乎并不表明实际收到了 HTTP 状态代码 409:

Unfortunately, the error produced does not seem to indicate that an HTTP status code 409 was actually received:

STRING Error:: error:Optional(Error Domain=NSURLErrorDomain Code=-999 "cancelled" UserInfo=0x7f9beb8efce0 {NSErrorFailingURLKey=https://host.com/a/path, NSLocalizedDescription=cancelled, NSErrorFailingURLStringKey=https://host.com/a/path})
  req:<NSMutableURLRequest: 0x7f9beb89d5e0> { URL: https://host.com/a/path }
  res:nil
  data:Optional("")
JSON Error:: error:Optional(Error Domain=NSURLErrorDomain Code=-999 "cancelled" UserInfo=0x7f9beb8efce0 {NSErrorFailingURLKey=https://host.com/a/path, NSLocalizedDescription=cancelled, NSErrorFailingURLStringKey=https://host.com/a/path})
  req:<NSMutableURLRequest: 0x7f9beb89d5e0> { URL: https://host.com/a/path }
  res:nil
  data:nil

此外,在发生错误时检索 HTTP 正文会很好,因为我的服务器端会在那里放置错误的文本描述.

Additionally, it would be nice to retrieve the HTTP body when an error occurs because my server-side will put a textual description of the error there.

问题
是否可以根据非 2xx 响应检索状态代码?
是否可以根据 2xx 响应检索特定状态代码?
是否可以根据非 2xx 响应检索 HTTP 正文?

Questions
Is it possible to retrieve the status code upon a non-2xx response?
Is it possible to retrieve the specific status code upon a 2xx response?
Is it possible to retrieve the HTTP body upon a non-2xx response?

谢谢!

推荐答案

适用于 Swift 3.x/Swift 4.0/Swift 5.0 用户Alamofire >= 4.0/Alamofire >= 5.0

For Swift 3.x / Swift 4.0 / Swift 5.0 users with Alamofire >= 4.0 / Alamofire >= 5.0

response.response?.statusCode

<小时>

更详细的例子:


More verbose example:

Alamofire.request(urlString)
        .responseString { response in
            print("Success: (response.result.isSuccess)")
            print("Response String: (response.result.value)")

            var statusCode = response.response?.statusCode
            if let error = response.result.error as? AFError {  
                statusCode = error._code // statusCode private                 
                switch error {
                case .invalidURL(let url):
                    print("Invalid URL: (url) - (error.localizedDescription)")
                case .parameterEncodingFailed(let reason):
                    print("Parameter encoding failed: (error.localizedDescription)")
                    print("Failure Reason: (reason)")
                case .multipartEncodingFailed(let reason):
                    print("Multipart encoding failed: (error.localizedDescription)")
                    print("Failure Reason: (reason)")
                case .responseValidationFailed(let reason):
                    print("Response validation failed: (error.localizedDescription)")
                    print("Failure Reason: (reason)")

                    switch reason {
                    case .dataFileNil, .dataFileReadFailed:
                        print("Downloaded file could not be read")
                    case .missingContentType(let acceptableContentTypes):
                        print("Content Type Missing: (acceptableContentTypes)")
                    case .unacceptableContentType(let acceptableContentTypes, let responseContentType):
                        print("Response content type: (responseContentType) was unacceptable: (acceptableContentTypes)")
                    case .unacceptableStatusCode(let code):
                        print("Response status code was unacceptable: (code)")
                        statusCode = code
                    }
                case .responseSerializationFailed(let reason):
                    print("Response serialization failed: (error.localizedDescription)")
                    print("Failure Reason: (reason)")
                    // statusCode = 3840 ???? maybe..
                default:break
                }

                print("Underlying error: (error.underlyingError)")
            } else if let error = response.result.error as? URLError {
                print("URLError occurred: (error)")
            } else {
                print("Unknown error: (response.result.error)")
            }

            print(statusCode) // the status code
    } 

(Alamofire 4 包含一个全新的错误系统,请看 此处 了解详情)

(Alamofire 4 contains a completely new error system, look here for details)

对于 Swift 2.x 用户,Alamofire >= 3.0

Alamofire.request(.GET, urlString)
      .responseString { response in
             print("Success: (response.result.isSuccess)")
             print("Response String: (response.result.value)")
             if let alamoError = response.result.error {
               let alamoCode = alamoError.code
               let statusCode = (response.response?.statusCode)!
             } else { //no errors
               let statusCode = (response.response?.statusCode)! //example : 200
             }
}

这篇关于Swift Alamofire:如何获取 HTTP 响应状态代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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