小编典典

Swift-将NSURLResponse向下转换为NSHTTPURLResponse以获得响应代码

swift

我正在使用NSURLRequest在SWIFT中构建其余查询

var request : NSURLRequest = NSURLRequest(URL: url)

var connection : NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: false)!
connection.start()

我的问题是如何从返回的响应中获取响应代码:

    func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {
//...
}

根据Apple的说法:
NSHTTPURLResponse这是的子类,NSURLResponse具有状态代码,但是我不确定如何向下转换响应对象,以便可以看到响应代码。

这似乎没有削减:

println((NSHTTPURLResponse)response.statusCode)

谢谢


阅读 719

收藏
2020-07-07

共1个答案

小编典典

使用可选的强制转换(as?)和可选的绑定(if let):

func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {
    if let httpResponse = response as? NSHTTPURLResponse {
        println(httpResponse.statusCode)
    } else {
        assertionFailure("unexpected response")
    }
}

或单线

let statusCode = (response as? NSHTTPURLResponse)?.statusCode ?? -1

-1如果响应不是HTTP响应(在HTTP请求中不应发生),则将状态代码设置为的位置。

2020-07-07