views:

34

answers:

1

Probably really a rookie question here about xcode (for the iphone)..

When I issue this command;

NSString *externalData = [NSData dataWithContentsOfURL:[NSURL URLWithString: @"http://blah.com/userlist.txt"]];

I can see it's download from my webserver. How can I make this 1 line show in a label?

I tried; label.text = externalData; [externalData release];

But this doesn't seem to work..it seems to crash the app in the simulator. Any ideas?

+5  A: 

It crashes because +dataWithContentsOfURL: returns an NSData* which is not an NSString*. You want +stringWithContentsOfURL: instead. Note though, that this will block the main thread, which may not be desirable.

Edit:

To be clear, code like this:

NSString* foo = [NSString stringWithContentsOfURL:...];

Where you replace the appropriate sections of code with your own values.

jer
Deprecated. Use stringWithContentsOfURL:encoding:error: if you know the encoding or stringWithContentsOfURL:usedEncoding:error: which tells you what encoding it used to interpret the data. The latter is probably sensible for text/* content-types with a charset= parameter.
tc.
Good point and good catch. I haven't used these classes of methods in a long time, so I don't keep up on their depreciation.
jer
Thanks for your quick reply.I tried NSURL *url = [NSURL URLWithString:@"http://www.blah.com/xcode/userlist.txt"];NSString *content = [NSString stringWithContentsOfURL:url encoding:NSASCIIStringEncoding];label.text = *content;It tells me;Incompatible type for argument 1 of setText .. I assume I have to do some conversion here?I tried;label.text = [NSString stringWithFormat:@"%s",content];But that just isn't is..Thanks for your help so far!
Alex van Es
I eventually got it working with; content = [NSString stringWithContentsOfURL:[NSURLURLWithString:@"http://www.iblah.com/xcode/userlist.txt"] encoding: 1 error: NULL];label.text = content;And in the .h file I had to put NSString *content;And that did the job.Thanks all
Alex van Es