Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
281 views
in Technique[技术] by (71.8m points)

iphone - Saving text file to documents directory in iOS 7

I am trying to save a plain text file to the Documents directory in iOS 7. Here is my code:

//Saving file
NSFileManager *fileManager = [[NSFileManager alloc] init];
NSArray *urls = [fileManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask];

NSString *url = [NSString stringWithFormat:@"%@", urls[0]];

NSString *someText = @"Random Text To Be Saved";
NSString *destination = [url stringByAppendingPathComponent:@"File.txt"];

NSError *error = nil;

BOOL succeeded = [someText writeToFile:destination atomically:YES encoding:NSUTF8StringEncoding error:&error];

if (succeeded) {
    NSLog(@"Success at: %@",destination);
} else {
    NSLog(@"Failed to store. Error: %@",error);
}

Here is the error I am getting:

2013-10-13 16:09:13.848 SavingFileTest[13675:a0b] Failed to store. Error: Error Domain=NSCocoaErrorDomain Code=4 "The operation couldn’t be completed. (Cocoa error 4.)" UserInfo=0x1090895f0 {NSFilePath=file:/Users/Username/Library/Application%20Support/iPhone%20Simulator/7.0-64/Applications/F5DA3E33-80F7-439B-A9AF-E8C7FC4E1630/Documents/File.txt, NSUserStringVariant=Folder, NSUnderlyingError=0x10902aeb0 "The operation couldn’t be completed. No such file or directory"}

I can't figure out why I am getting this error running on the simulator. This works if I use the NSTemporaryDirectory().

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

From Apple's Xcode Template:

/**
 Returns the URL to the application's Documents directory.
 */
- (NSURL *)applicationDocumentsDirectory {
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory 
         inDomains:NSUserDomainMask] lastObject];
}

You can save like this:

NSString *path = [[self applicationDocumentsDirectory].path 
                       stringByAppendingPathComponent:@"fileName.txt"];
[sampleText writeToFile:path atomically:YES
                       encoding:NSUTF8StringEncoding error:nil];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...