Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a .txt file programmatically on iOS

I am a new iOS developer. I want to create an app that will auto-create new *.txt files in the app's folder. I could only find how to open, close, save, write, and read - not create. How can I create new files? Thanks.

like image 499
kemdo Avatar asked Nov 29 '22 07:11

kemdo


1 Answers

Use the following code to write/create a .txt file in your app's Documents directory. It should be pretty self-explanatory.

NSError *error;
NSString *stringToWrite = @"1\n2\n3\n4";
NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"myfile.txt"];
[stringToWrite writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];

And to retrieve the text file:

NSString *str = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
NSLog(@"%@", str);
like image 73
rebello95 Avatar answered Dec 05 '22 12:12

rebello95