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?

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.
    – Matz
    Commented May 4, 2015 at 13:55
  • 5
    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 head
    – inorganik
    Commented May 4, 2015 at 14:33

3 Answers 3

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
}];
3
  • 1
    Can we be sure this is going to indeed be an instance of NSHTTPURLResponse, or is it worth checking with isKindOfClass: or respondsToSelector:?
    – Tim
    Commented Feb 3, 2015 at 17:07
  • @TimArnold yes, it's an instance of NSHTTPURLResponse, so it has all the properties and methods of that class.
    – inorganik
    Commented Feb 3, 2015 at 19:48
  • 15
    As the docs say: Whenever you make an HTTP request, the NSURLResponse object you get back is actually an instance of the NSHTTPURLResponse class. Commented Mar 13, 2015 at 19:42
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()
}
2
  • Question tagged with objective-c.
    – trojanfoe
    Commented Jan 21, 2016 at 9:26
  • 5
    It would be the same methods and order for objective-c.
    – Bjarte
    Commented Jan 26, 2016 at 11:48
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()

Not the answer you're looking for? Browse other questions tagged or ask your own question.