Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
452 views
in Technique[技术] by (71.8m points)

Swift Alamofire: How to get the HTTP response status code

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

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

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.

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?

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 contains a completely new error system, look here for details)

For Swift 2.x users with 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
             }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...