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

时间:2014-10-04 09:18:04

标签: ios swift nsurlconnection nsurlrequest

如何在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?

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

7 个答案:

答案 0 :(得分:65)

传入对响应的引用,因此它被填充然后检查结果并将其转换为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)")
}

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

答案 1 :(得分:52)

@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()

答案 2 :(得分:10)

Swift 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()

答案 3 :(得分:7)

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

extension URLResponse {

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

答案 4 :(得分:6)

使用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()`

答案 5 :(得分:2)

如果您使用Just库,它就像:

一样简单
Just.get("URL_IS_HERE").statusCode

答案 6 :(得分:0)

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

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

获取请求的响应-

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