Cover by Alasdair Allan

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

Getting Data from the Internet

If you want to retrieve data from the Internet and process it programmatically, rather than just display it in a view, you should use the NSURLConnection class. While it’s more complicated than the UIWebView we looked at earlier in the chapter, it’s inherently more flexible.

The NSURLConnection class can make both synchronous and asynchronous requests to download the contents of a URL, and the associated delegate methods provide feedback and control for asynchronous requests.

Synchronous Requests

The easiest, but not the best, way to use the NSURLConnection class is to make a synchronous request for data:

NSString *url = @"http://www.apple.com";
NSURLRequest *request =
   [NSURLRequest requestWithURL:[NSURL URLWithString:url]];

NSURLResponse *response = nil;
NSError *error = nil;
NSData *content = [NSURLConnection sendSynchronousRequest:request
  returningResponse:&response error:&error];

NSString *string = [[NSString alloc] initWithData:content
  encoding:NSUTF8StringEncoding];
NSLog(@"response: %@", string);

sendSynchronousRequest: is a convenience method built on top of the asynchronous request code. It’s important to note that if you use this method the calling thread will block until the data is loaded or the request times out. If the calling thread is the main thread of your application, your application will freeze while the request is being made. This is generally considered not a good thing from a UI perspective; I strongly encourage you to use the asynchronous ...

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required