1

I'd like to be able to get my iphone to load a URL( or really the file that the url points to) into a string. The reason I want to be able to do this is so that I can then parse the string looking for tags and extract some values from it.

The files are mostly webpages so html or .asp etc.

Anybody able to give me some hints on what I need to do to achieve this kinda of thing?

Many Thanks, -Code

2 Answers2

3

First get the URL

NSURL *anUrl = [NSURL URLWithString:@"http://google.com"];

Then turn it into a string

NSError *error;
NSString *htmlString = [NSString stringWithContentsOfURL:anUrl encoding:NSUTF8Encoding error:&error];

UPDATE:

There is documentation on getting the contents of an URL by using NSURLConnection from the ADC site

From there you can get the string representation of the downloaded data using

NSString *htmlString = [[NSString alloc] initWithData:urlData encoding:NSUTF8Encoding];
Abizern
  • 146,289
  • 39
  • 203
  • 257
  • 2
    Note that this will block the calling thread of the application until the URL is fully downloaded. If you need the download to proceed asynchronously, you should use `NSURLConnection`. – Justin Spahr-Summers Dec 02 '10 at 02:02
  • Good point - But it's a start and the OP did ask for a hint. ;-) – Abizern Dec 02 '10 at 03:41
2

I appreciate that this has been asked and answered, but I would strongly suggest that you consider not using NSString's stringWithContentsOfURL:encoding:error: method for this. If there's one message Apple has tried to send to iOS developers over the past year it is this: Do not make synchronous network calls on the main thread.

If that request takes more than twenty seconds to respond, which is not at all unlikely with a 3G or EDGE connection, and certainly possible on a WiFi connection, iOS will kill your app. More importantly, if it takes more than about half a second to return you're going to anger your users as they fiddle with their unresponsive phones.

NSURLConnection is not terribly difficult to use, and will allow your device to continue responding to events while it's downloading content.

Adam Milligan
  • 2,826
  • 19
  • 17