I'm trying to write a simple string to file, using the following code:
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fileName = [NSString stringWithFormat:@"%@/textfile.txt",
documentsDirectory];
NSString *content = @"Test Content";
NSError *error = nil;
[content writeToFile:fileName atomically:NO encoding:NSStringEncodingConversionAllowLossy error:&error];
NSLog(@"Error %@ %@", fileName, error);
But the file is'nt written and error is null.
I'm running the code in the iOS Simulator and expect the file to be written to a location like: /Users/user/Library/Developer/CoreSimulator/Devices/85DDC17D-A771-40D9-99BE-71FF6B60D2DF/data/Containers/Data/Application/BD30A945-25DB-4ECE-B7F7-E9C20C6691C7/Documents/textfile.txt (the Path of fileName from NSLog).
As @rckoenes pointed out it was an error in the rest of my code. I have a function that deletes all files in "documents", i just didn't remember that i had this function and because of the length of the code (>5000 lines) it was hard to find. Thank you all!
working with URLs is a bit reliable way, so I would re-work your idea slightly like eg this:
NSURL *_documentFolder = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
NSURL *_fileURL = [_documentFolder URLByAppendingPathComponent:@"textFile.txt"];
NSError *_error = nil;
BOOL _success = [@"hello!" writeToURL:_fileURL atomically:TRUE encoding:NSUTF8StringEncoding error:&_error];
that works perfectly on simulator and on real device too, and the file textFile.txt
will have the content hello!
.
NOTE: if the _success
value is FALSE
, you can get more information about the reason via a the _error
, even if you'd just log it to the debug-console. I have not isolated the NSString
in my example, but you can replace it with your own instance.
please check below code:
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filePath = [[pathsobjectAtIndex:0]stringByAppendingPathComponent:@"textfile.txt"];
NSString *temp = [[NSString alloc] initWithString:@"Test Content"];
[temp writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.