Jeef
Jeef

Reputation: 27285

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

Upvotes: 10

Views: 7689

Answers (1)

Martin R
Martin R

Reputation: 540065

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

Upvotes: 16

Related Questions