NSURLResponse - How to get status code?

IosObjective C

Ios Problem Overview


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?

Ios Solutions


Solution 1 - Ios

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
}];

Solution 2 - Ios

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()
}

Solution 3 - Ios

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioninorganikView Question on Stackoverflow
Solution 1 - IosinorganikView Answer on Stackoverflow
Solution 2 - IosBjarteView Answer on Stackoverflow
Solution 3 - IosHaroldo GondimView Answer on Stackoverflow