Say I want to get the HTML of
http://www.google.com
as a String using some built-in classes of the Cocoa Touch framework.
What is the least amount of code I need to write?
I've gotten this far, but can't figure out how to progress. There must be an easier way.
CFHTTPMessageRef req;
NSURL *url = [NSURL URLWithString:@"http://www.google.com"];
req = CFHTTPMessageCreateRequest(kCFAllocatorDefault,
CFSTR("GET"),
(CFURLRef)url,
kCFHTTPVersion1_1);
The quickest way is to use NSString's +stringWithContentsOfURL:
method. However, this is a modal call, and your application will be non-responsive while it runs. You can either move it to a background thread, or use the NSURLConnection class to make a proper, asynchronous request.
One way to do this is as follows, however as Ben Gottlieb points out, this is a synchronouseRequest and will cause your program's execution to wait on the return of this function call, possibly making your application non-responsive.
NSURL *url = [ NSURL URLWithString: @"http://www.google.com"];
NSURLRequest *req = [ NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:30.0 ];
NSError *err;
NSURLResponse *res;
NSData *d = [ NSURLConnection sendSynchronousRequest:req
returningResponse:&res
error:&err ];
You can find information on writing the proper delegate methods to handle a Asynchronous Connection here on the Apple dev-docs.