问题描述
我正在使用NSURLRequest在SWIFT中构建休息查询
var request:NSURLRequest = NSURLRequest(URL:url)
var connection:NSURLConnection = NSURLConnection(请求:request,delegate:self,startImmediately:false)!
connection.start()
我的问题是如何获取响应代码返回的响应:
func connection(didReceiveResponse:NSURLConnection!,didReceiveResponse response:NSURLResponse!){
/ / ...
}
根据Apple的说法: NSHTTPURLResponse
这是 NSURLResponse的子类
有一个状态代码,但我不知道如何转发我的响应对象,以便我可以看到响应代码。 / p>
这似乎没有削减它:
println(( NSHTTPURLResponse)response.statusCode)
谢谢
使用可选的强制转换( as?
)和可选绑定(如果让
):
func connection(didReceiveResponse:NSURLConnection!,didReceiveResponse response:NSURLResponse!){
if let httpResponse = respon作为? NSHTTPURLResponse {
println(httpResponse.statusCode)
} else {
assertionFailure(意外回复)
}
}
或作为单行
让statusCode =(响应为?NSHTTPURLResponse)?. statusCode ?? -1
其中状态代码将设置为 -1
如果响应不是HTTP响应
(对于HTTP请求不应该发生)。
I'm building rest queries in SWIFT using NSURLRequest
var request : NSURLRequest = NSURLRequest(URL: url)
var connection : NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: false)!
connection.start()
My question is how to do i get response code out of the response that is returned:
func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {
//...
}
According to Apple: NSHTTPURLResponse
which is a subclass of NSURLResponse
has a status code but I'm not sure how to downcast my response object so i can see the response code.
This doesn't seem to cut it:
println((NSHTTPURLResponse)response.statusCode)
Thanks
Use an optional cast (as?
) with optional binding (if let
):
func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {
if let httpResponse = response as? NSHTTPURLResponse {
println(httpResponse.statusCode)
} else {
assertionFailure("unexpected response")
}
}
or as a one-liner
let statusCode = (response as? NSHTTPURLResponse)?.statusCode ?? -1
where the status code would be set to -1
if the response is not an HTTP response(which should not happen for an HTTP request).
这篇关于Swift - 向下转换NSURLResponse到NSHTTPURLResponse以获取响应代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!