Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
392 views
in Technique[技术] by (71.8m points)

ios - Swift - downcast NSURLResponse to NSHTTPURLResponse in order to get response code

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...