我使用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)
谢谢
答案 0 :(得分:16)
使用可选的强制转换(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
如果响应不是HTTP响应,则状态代码将设置为-1
(对于HTTP请求不应该发生这种情况。)