8

I am sort of new to developing view-based iPhone applications, and I need to download this "txt" file off the internet and save it into the documents folder of the app. Can anyone show me simply how I can do this? The txt file is of a tiny size, so I wouldn't need any User interface objects...

Thanks,

Kevin

LearnCocos2D
  • 64,083
  • 20
  • 128
  • 214
lab12
  • 6,370
  • 21
  • 65
  • 106

2 Answers2

11
NSError *err = nil;
NSString *url = [[NSString stringWithFormat:@"http://myurl.com/mypage"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *myTxtFile = [NSString stringWithContentsOfURL:[NSURL URLWithString:url] encoding:NSUTF8StringEncoding error:&err];
if(err != nil) {
    //HANDLE ERROR HERE
}

Then to save it you can use:

[[NSUserDefaults standardUserDefaults] setObject:myTxtFile forKey:@"MyFile"];

And to retrieve it:

NSString *myTxtFile = [[NSUserDefaults standardUserDefaults] stringForKey:@"MyFile"];

Updated to reflect Joe's input

David Kanarek
  • 12,541
  • 5
  • 44
  • 61
  • Where is the MyFile.txt going to be? I've checked in the documents and its not there... – lab12 Feb 22 '10 at 01:32
  • 1
    Sorry, it's not actually in the documents folder, it's in the user defaults. You can retrieve it using the last line in my answer. Is there a specific reason it must be in the documents folder? – David Kanarek Feb 22 '10 at 01:40
  • No, actually, I thought it would be easier to find it in the Documents folder. :D. – lab12 Feb 22 '10 at 01:45
  • If I were to view this text file into a UITextView, do you by any chance know how to do this? – lab12 Feb 22 '10 at 01:47
  • 1
    `[myUITextView setText:myTxtFile];` – David Kanarek Feb 22 '10 at 02:06
  • Note that you do NOT need to allocate an NSError object as shown in the code above. Just initialize it to nil, and pass its address on in to the function. The stringWithContentsOfURL function itself will allocate an (autoreleased) NSError object for you if it has an error to report. – Joe Strout Mar 27 '12 at 15:37
1

Hey you can write the string content to the file in the document folder like this:

//get the documents directory:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

//make a file name to write the data to using the documents directory:

NSString *fileName = [NSString stringWithFormat:@"%@/textfile.txt",documentsDirectory];

//save content of myTxtFile to the documents directory

**[myTxtFile writeToFile:fileName atomically:NO encoding:NSStringEncodingConversionAllowLossy error:nil];**

After executing this, you'll find a file named textfile.txt in the document folder with the content stored in it..

Cheers!!!

Kanan Vora
  • 2,104
  • 1
  • 16
  • 26
  • why use `NSStringEncodingConversionAllowLossy` ? also, you didn't mention the class of `myTxtFile` – Raptor Mar 27 '13 at 08:02