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
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
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!!!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With