Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSURLResponse - How to get status code?

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?

like image 225
inorganik Avatar asked Aug 21 '14 16:08

inorganik


2 Answers

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 }]; 
like image 90
inorganik Avatar answered Oct 04 '22 19:10

inorganik


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() } 
like image 20
Bjarte Avatar answered Oct 04 '22 21:10

Bjarte