NSURLResponse - How to get status code?
Asked Answered
R

3

97

I have a simple NSURLRequest:

[NSURLConnection sendAsynchronousRequest:myRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
    // do stuff with response if status is 200
}];

How do I get the status code to make sure the request was ok?

Rebbecarebbecca answered 21/8, 2014 at 16:11 Comment(2)
I'm not sure, but you needn't to check the 200 status-code. If your server sends another status-code, you will get an error-object in the completionHandler and can check.Mallard
There are other status codes that represent results that aren't errors, like redirects or not founds, and probably others (auth related, etc) that I can't think of off the top of my headRebbecarebbecca
R
221

Cast an instance of NSHTTPURLResponse from the response and use its statusCode method.

[NSURLConnection sendAsynchronousRequest:myRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
    NSLog(@"response status code: %ld", (long)[httpResponse statusCode]);
    // do stuff
}];
Rebbecarebbecca answered 21/8, 2014 at 16:11 Comment(3)
Can we be sure this is going to indeed be an instance of NSHTTPURLResponse, or is it worth checking with isKindOfClass: or respondsToSelector:?Pandemonium
@TimArnold yes, it's an instance of NSHTTPURLResponse, so it has all the properties and methods of that class.Rebbecarebbecca
As the docs say: Whenever you make an HTTP request, the NSURLResponse object you get back is actually an instance of the NSHTTPURLResponse class.Bostick
U
33

In Swift with iOS 9 you can do it this way:

if let url = NSURL(string: requestUrl) {
    let request = NSMutableURLRequest(URL: url, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 300)
    let config = NSURLSessionConfiguration.defaultSessionConfiguration()
    let session = NSURLSession(configuration: config)

    let task = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
        if let httpResponse = response as? NSHTTPURLResponse {
            print("Status code: (\(httpResponse.statusCode))")

            // do stuff.
        }
    })

    task.resume()
}
Unction answered 3/11, 2015 at 12:2 Comment(2)
Question tagged with objective-c.Carny
It would be the same methods and order for objective-c.Unction
B
15

Swift 4

let task = session.dataTask(with: request, completionHandler: { data, response, error -> Void in

    if let httpResponse = response as? HTTPURLResponse {
        print("Status Code: \(httpResponse.statusCode)")
    }

})

task.resume()
Bobbie answered 23/10, 2017 at 18:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.