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
class. While it’s more complicated than the
UIWebView we looked at earlier in the chapter,
it’s inherently more flexible.
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.
The easiest, but not the best, way to use the
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 ...