Quick and dirty NSURL request

I started looking at Apple’s NSURL* family of classes today, as I’m about to start interfacing my GFF viewer application with an online BLAT search tool (for in-house purposes only — this isn’t going to be available in the release version) and I was a little shocked to find this line in Apple’s documentation:

In order to download the contents of a URL, an application needs to provide a delegate object that, at a minimum, implements the following delegate methods: connection:didReceiveResponse:, connection:didReceiveData:, connection:didFailWithError: and connectionDidFinishLoading:

In other words, one would have to first establish an NSURLConnection (having already formed an NSURLRequest) and then implement four NSURLConnection delegate methods just to download a single HTML file. This all seems a little excessive for me just downloading a single HTML file.

After a little bit of playing around, I’ve found that the following code works just great for downloading a single HTML file:
NSURL *fileURL;
NSMutableString *fileContents;
fileURL = [NSURL URLWithString:@"http://127.0.0.1/index.html"];
fileContents = [[NSMutableString alloc] initWithContentsOfURL:fileURL];

A quick NSLog(@”%@”,fileContents); reveals that fileContents does indeed contain index.html from localhost. Good stuff.

As a piece of code, this is rather unwholesome on all fronts. There is no error handling anywhere to be seen. Not in the formation of the URL, not in the retrieval of the URL. Zilch. Errors are not handled. Anything could happen. It’s a mini adventure.

Bonus information!
Just out of interest, I checked my Apache access-log after this request to find that NSMutableString’s initWithContentsOfURL: method provides the user agent string: “CFNetwork/129.20” (as of 10.4.10).

Leave a Reply

Your email address will not be published. Required fields are marked *