Saving text file to documents directory in iOS 7
Asked Answered
W

3

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

Wavemeter answered 13/10, 2013 at 23:33 Comment(3)
did you verify that that directory exists? it looks like valid codeValeriavalerian
I typed this in the terminal: cd Library/Application Support and it won't let me type the space correctly for Application Support.Wavemeter
add quotes around the pathValeriavalerian
D
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];
Deadhead answered 13/10, 2013 at 23:44 Comment(4)
@Deadhead I'm curious why the application directory should be the lastObject of the array of NSURL objects?Washing
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).Deadhead
In Swift: NSSearchPathForDirectoriesInDomains(.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).first as StringCarburet
Place a slash "/" before file name: NSString *path = [[self applicationDocumentsDirectory].path stringByAppendingPathComponent:@"/fileName.txt"]; Otherwise it will not save the file in Documents directory.Naji
N
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!
}
Naji answered 6/5, 2016 at 10:33 Comment(1)
Swift 5: let filePath = self.applicationDocumentsDirectory().path?.appending(fileName)Rosalie
P
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];

    }
Ptomaine answered 25/4, 2014 at 21:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.