4

In my iPhone app, how can I download a .txt file from the web, and then get it's contents into an NSString. For instance, say the text file was located at http://www.somewebsite.com/textfile.txt

Then what I want to do is:

if(user has internet connection)
   NSString *textFile = download text file from http://www.somewebsite.com/textfile.txt
else
  NSLog(@"user has no internet");

Can someone show me code to do this?

StanLe
  • 5,037
  • 9
  • 38
  • 41
  • Using NSURLRequest you can easily download the file, save this file and use it according to your requirements. You can take help from http://stackoverflow.com/questions/3464252/how-to-download-a-file-by-using-nsurlconnection. – Mobile Developer iOS Android Jul 02 '11 at 05:45

3 Answers3

2

Check out this library to download files via http: http://allseeing-i.com/ASIHTTPRequest/

Nick B
  • 1,101
  • 9
  • 19
  • that seems to be a bit complicated. I only need to download a txt file. any simpler ideas? that download is way too complex for me. I'm more of a noobie. – StanLe Jul 02 '11 at 04:55
  • See if anyone else has a suggestion, but that's actually the simplest way I've found to download a file via http on the iPhone, unfortunately. – Nick B Jul 02 '11 at 05:14
  • 1
    To download a file you can simply instantiate a string with `stringWithContentsOfURL:`. You don't need the whole library for this. – Eimantas Jul 02 '11 at 06:08
1

To test for internet connectivity, look at Apple's Reachability example. It has all the code you'll need for that.

To get the file, you may want to check out this SO post: Can I make POST or GET requests from an iphone application? and its relevant follow-up post: Making GET and POST Requests from an iPhone Application - Clarification Needed

Community
  • 1
  • 1
PengOne
  • 48,188
  • 17
  • 130
  • 149
0

Check NSURLConnection classes.

Rahul Vyas
  • 28,260
  • 49
  • 182
  • 256