Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to download a text file with iPhone SDK?

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

like image 975
lab12 Avatar asked Feb 22 '10 00:02

lab12


2 Answers

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

like image 193
David Kanarek Avatar answered Nov 10 '22 12:11

David Kanarek


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!!!

like image 20
Kanan Vora Avatar answered Nov 10 '22 12:11

Kanan Vora