How do I save an NSString as a .txt file on my apps local documents directory?

99封情书 提交于 2019-11-30 03:08:24
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents directory

NSError *error;
BOOL succeed = [myString writeToFile:[documentsDirectory stringByAppendingPathComponent:@"myfile.txt"]
      atomically:YES encoding:NSUTF8StringEncoding error:&error];
if (!succeed){
    // Handle error here
}

Something like this:

NSString *homeDirectory;
homeDirectory = NSHomeDirectory(); // Get app's home directory - you could check for a folder here too.
BOOL isWriteable = [[NSFileManager defaultManager] isWritableFileAtPath: homeDirectory]; //Check file path is writealbe
// You can now add a file name to your path and the create the initial empty file

[[NSFileManager defaultManager] createFileAtPath:newFilePath contents:nil attributes:nil];

// Then as a you have an NSString you could simple use the writeFile: method
NSString *yourStringOfData;
[yourStringOfData writeToFile: newFilePath atomically: YES];
RaffAl

He is how to save NSString into Documents folder. Saving other types of data can be also realized that way.

- (void)saveStringToDocuments:(NSString *)stringToSave {

 NSString *documentsFolder = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
 NSString *fileName = [NSString stringWithString:@"savedString.txt"];

 NSString *path = [documentsFolder stringByAppendingPathComponent:fileName];

 [[NSFileManager defaultManager] createFileAtPath:path contents:[stringToSave dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];
}

you could use NSUserDefaults

Saving:

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:@"TextToSave" forKey:@"keyToLookupString"];

Reading:

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *myString = [prefs stringForKey:@"keyToLookupString"];

I was using this method to save some base64 encoded image data to the disk. When opening the text file on my computer I kept having trouble reading the data because of some line breaks and returns being added automatically.

The following code fixes this issue:

myString = [myString stringByReplacingOccurrencesOfString:@"\n" withString:@""];
myString = [myString stringByReplacingOccurrencesOfString:@"\r" withString:@""];

// write string to disk
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!