November 27, 2009

Remote File Request to NSString in Objective C

A current side project in Obj C that I m working on required a way to fetch a remote HTML file and parse through it to get the url of links and images. The first step required a way to get a remote file and store it as a NSString. The code below is an example of how to so.

NSString *url = @"http://www.google.com";
NSURLRequest *urlrequest = [ [NSURLRequest alloc] initWithURL: [NSURL URLWithString:url] ];
NSData *returnData = [ NSURLConnection sendSynchronousRequest:urlrequest returningResponse: nil error: nil ];
NSString *returnstring = [[NSString alloc] initWithData:returnData encoding:NSASCIIStringEncoding];

Tested on OS X 10.5+ with GCC 4.2

No comments: