Jan Nowicki Jan Nowicki - 5 months ago 8
Objective-C Question

How to download text from web in iOS?

I want to show text from txt file from server in label. For example I have

http://www.example.com/test.txt
file on server and here is some text and I want to show this downloaded text as label in my app. I tried

- (IBAction)getText:(id)sender {
NSURL *url = [NSURL URLWithString:@"http://http://mrrandom.cba.pl/test.txt"];
NSString *content = [NSString stringWithContentsOfURL:url encoding:NSStringEncodingConversionAllowLossy error:nil];
_label.text = content;
}


but it didn't work for me. Do you have any ideas? Thanks for help!

Answer

You have a typo in your url.

Instead of writing

http://http://mrrandom.cba.pl/test.txt

You should write

http://mrrandom.cba.pl/test.txt

Also, you should consider doing "downloads" on a background thread using NSURLSession.

For more info about performing download on iOS, please refer to the documentation about the URL Loading System.

Comments