Swift - Downcast Nsurlresponse to Nshttpurlresponse in Order to Get Response Code

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

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

How to get the status code from HTTP Get in swift?

NSURLResponse do not have status code, but NSHTTPURLResponse does. So cast it:

let httpResponse = response as NSHTTPURLResponse
httpResponse.statusCode

When is a NSURLResponse not a NSHTTPURLResponse?

It is ok if you are sure that your connection runs via HTTP protocol:

An NSHTTPURLResponse object represents a response to an HTTP URL load request. It’s a subclass of NSURLResponse that provides methods for accessing information specific to HTTP protocol responses.

If you are connecting via FTP, for example, then casting NSURLResponse to NSHTTPURLResponse will be incorrect.

How do you test a URL and get a status code in Swift 3?

try this out to give you the status codes of the responses - 200, 404 etc:

let url = URL(string: fullURL)

let task = URLSession.shared.dataTask(with: url!) { _, response, _ in
if let httpResponse = response as? HTTPURLResponse {
print(httpResponse.statusCode)
}
}

task.resume()

You could also do the same, simply replacing the with: url! to use the request var as you defined in your example e.g. let task = URLSession.shared.dataTask(with: request) {...} But in this example I don't think you need to really.



Related Topics



Leave a reply



Submit