views:

1106

answers:

1

Hello everybody,

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

+3  A: 
NSError *err = [[[NSError alloc] init] autorelease];
NSString *url = [[NSString stringWithFormat:@"http://myurl.com/mypage"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *myTxtFile = [NSString stringWithContentsOfURL:[NSURL URLWithString:url] encoding:NSUTF8StringEncoding error:&err];
if(err.code != 0) {
    //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"];
David Kanarek
Where is the MyFile.txt going to be? I've checked in the documents and its not there...
Kevin
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
No, actually, I thought it would be easier to find it in the Documents folder. :D.
Kevin
If I were to view this text file into a UITextView, do you by any chance know how to do this?
Kevin
`[myUITextView setText:myTxtFile];`
David Kanarek
Thank you soo much!
Kevin
Happy to help. Good luck.
David Kanarek