我正在使用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的一个子类,它有一个状态代码,但我不知道如何downcast我的响应对象,所以我可以看到响应代码.
这似乎没有削减它:
println((NSHTTPURLResponse)response.statusCode)
谢谢
解决方法
使用可选的cast(as?)和可选的绑定(如果允许的话):
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请求中).