25

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().

3 Answers3

61

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];
Mundi
  • 79,884
  • 17
  • 117
  • 140
  • 1
    @Mundi I'm curious why the application directory should be the `lastObject` of the array of `NSURL` objects? – George Apr 22 '14 at 06:10
  • 3
    Convenience. The expected result is an array with one element, so you could use `[0]` (which could crash if the array is somehow empty), or alternatively `firstObject` or `lastObject` (which will not crash but simply return `nil`). – Mundi Apr 22 '14 at 07:35
  • In Swift: `NSSearchPathForDirectoriesInDomains(.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).first as String` – Berik Mar 31 '15 at 23:14
  • Place a slash "/" before file name: NSString *path = [[self applicationDocumentsDirectory].path stringByAppendingPathComponent:@"/fileName.txt"]; Otherwise it will not save the file in Documents directory. – Syed Asad Ali May 06 '16 at 10:39
4

Mundi's answer in Swift:

    let fileName = "/File Name.txt"
    let filePath = self.applicationDocumentsDirectory().path?.stringByAppendingString(fileName)

    do {
        try strFileContents.writeToFile(filePath!, atomically: true, encoding: NSUTF8StringEncoding)
        print(filePath)
    }
    catch {
        // error saving file
    }

func applicationDocumentsDirectory() -> NSURL {

    return NSFileManager.defaultManager().URLsForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomains: NSSearchPathDomainMask.UserDomainMask).last!
}
Syed Asad Ali
  • 1,308
  • 1
  • 9
  • 14
  • Swift 5: let filePath = self.applicationDocumentsDirectory().path?.appending(fileName) – quin Apr 04 '23 at 15:05
1
    -(void)writeATEndOfFile:(NSString *)content2
    {
        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];

        if([[NSFileManager defaultManager] fileExistsAtPath:fileName])
        {
            NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:fileName];
            [fileHandle seekToEndOfFile];
            NSString *writedStr = [[NSString alloc]initWithContentsOfFile:fileName encoding:NSUTF8StringEncoding error:nil];
            content2 = [content2 stringByAppendingString:@"\n"];
            writedStr = [writedStr stringByAppendingString:content2];

            [writedStr writeToFile:fileName
                        atomically:NO
                          encoding:NSStringEncodingConversionAllowLossy
                             error:nil];
        }
        else {
            int n = [content2 intValue];
            [self writeToTextFile:n];
        }

    }   


 -(void) writeToTextFile:(int) value{
        //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];
        //create content - four lines of text
       // NSString *content = @"One\nTwo\nThree\nFour\nFive";

        NSString *content2 = [NSString stringWithFormat:@"%d",value];
        content = [content2 stringByAppendingString:@"\n"];
        //save content to the documents directory
        [content writeToFile:fileName
                  atomically:NO
                    encoding:NSStringEncodingConversionAllowLossy
                       error:nil];

    }
casillas
  • 16,351
  • 19
  • 115
  • 215