ios 如何在 Swift 上检查 sendSynchronousRequest 中的 Response.statusCode

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26191377/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 03:00:57  来源:igfitidea点击:

How To Check Response.statusCode in sendSynchronousRequest on Swift

iosswiftnsurlconnectionnsurlrequest

提问by hossein1448

How To check response.statusCode in SendSynchronousRequest in Swift The Code is Below :

如何在 Swift 中检查 SendSynchronousRequest 中的 response.statusCode 代码如下:

let urlPath: String = "URL_IS_HERE"
var url: NSURL = NSURL(string: urlPath)
var request: NSURLRequest = NSURLRequest(URL: url)
var response: AutoreleasingUnsafeMutablePointer<NSURLResponse?> = nil

var error: NSErrorPointer? = nil
var data = NSURLConnection.sendSynchronousRequest(request, returningResponse: response, error: nil) as NSData?

before and in objective c , we check response.statusCode With this : (long)response.statusCode but in swift i have no idea how can check response status Code

在目标 c 之前和中,我们检查 response.statusCode 用这个:(长)response.statusCode 但很快我不知道如何检查响应状态代码

回答by Daij-Djan

you pass in a reference to response so it is filled THEN you check the result and cast it to a HTTPResponse as only http responses declare the status code property.

您传入对响应的引用,以便填充然后检查结果并将其转换为 HTTPResponse,因为只有 http 响应声明了状态代码属性。

let urlPath: String = "http://www.google.de"
var url: NSURL = NSURL(string: urlPath)
var request: NSURLRequest = NSURLRequest(URL: url)
var response: NSURLResponse?

var data = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: nil) as NSData?

if let httpResponse = response as? NSHTTPURLResponse {
    println("error \(httpResponse.statusCode)")
}

note: in objC you would also use the same approach but if you use squared brackets, the compiler doesn't enforce the cast. Swift (being type safe) does enforce the cast always

注意:在 objC 中,您也将使用相同的方法,但如果您使用方括号,编译器不会强制执行转换。Swift(类型安全)确实始终强制执行强制转换

回答by DazChong

Swift 3 version for @GarySabo answer:

@GarySabo 的 Swift 3 版本回答:

let url = URL(string: "https://apple.com")!
let request = URLRequest(url: url)

let task = URLSession.shared().dataTask(with: request) {data, response, error in

    if let httpResponse = response as? HTTPURLResponse {
        print("statusCode: \(httpResponse.statusCode)")
    }

}
task.resume()

回答by Dasoga

Swift 3+

斯威夫特 3+

let dataURL = "https://myurl.com"
        var request = URLRequest(url: URL(string: dataURL)!)
        request.addValue("Bearer \(myToken)", forHTTPHeaderField: "Authorization")
        URLSession.shared.dataTask(with: request) { (data, response, error) in
            // Check if the response has an error
            if error != nil{
                print("Error \(String(describing: error))")
                return
            }

            if let httpResponse = response as? HTTPURLResponse{
                if httpResponse.statusCode == 401{
                    print("Refresh token...")
                    return
                }
            }

            // Get data success

        }.resume()

回答by eskimwier

I use an extension to URLResponse to simplify this one (Swift 3):

我使用 URLResponse 的扩展来简化这个(Swift 3):

extension URLResponse {

    func getStatusCode() -> Int? {
        if let httpResponse = self as? HTTPURLResponse {
            return httpResponse.statusCode
        }
        return nil
    }
}

回答by GarySabo

Cleaned up for Swift 2.0 using NSURLSession

使用 NSURLSession 清理 Swift 2.0

let urlPath: String = "http://www.google.de"
let url: NSURL = NSURL(string: urlPath)!
let request: NSURLRequest = NSURLRequest(URL: url)
var response: NSURLResponse?


let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request) {urlData, response, reponseError in

         if let httpResponse = response as? NSHTTPURLResponse {
             print("error \(httpResponse.statusCode)")  
          }

 }
 task.resume()
 //You should not write any code after `task.resume()`

回答by Rahul

Create extension to check valid/invalid response -

创建扩展以检查有效/无效响应 -

extension HTTPURLResponse {
     func isResponseOK() -> Bool {
      return (200...299).contains(self.statusCode)
     }
}

Get response from request -

从请求中获取响应 -

let task = URLSession.shared.dataTask(with: request) { (jsonData, response, error) in

                // post result on main thread
                DispatchQueue.main.async {

                    if let response = response as? HTTPURLResponse, response.isResponseOK() {
                        // assume if we don't receive any error then its successful
                        handler(true)
                    } else {
                        handler(false)
                    }
                }

            }
            task.resume()
        }

回答by Daniel Duan

If you use the Justlibrary it'd be as simple as:

如果你使用Just库,它会很简单:

Just.get("URL_IS_HERE").statusCode