Sirhc
Sirhc

Reputation: 538

How do i create a file in the default documents directory in an iOS app

I'm writing an app that needs to store some persistence information in file but i'm having trouble debugging the createFileAtPath:contents:attributes: function of NSFileManager, i have reduced the problem to the below piece of code.

NSFileManager *filemgr;
filemgr = [NSFileManager defaultManager];
NSString * fileName = @"newfile.txt";

NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *filePath = [documentsDirectory stringByAppendingPathComponent: fileName];
NSLog(@"full path name: %@", filePath);

// check if file exists
if ([filemgr fileExistsAtPath: filePath] == YES){
    NSLog(@"File exists");

}else {
    NSLog (@"File not found, file will be created");
    if (![filemgr createFileAtPath:filePath contents:nil attributes:nil]){
        NSLog(@"Create file returned NO");
    }
}

Since the function doesn't take an NSError object i'm having trouble finding out why exactly it is returning false.

From other examples i have seen here Write a file on iOS and here How to programmatically create an empty .m4a file of a certain length under iOS using CoreAudio on device? it should be ok to pass nil to both the contents and attributes parameters. I've tried specifying both parameters and receive the same result.

I'm thinking this may be a permissions issue but i'm unsure if the below code is the correct way to check permissions on a directory.

if ([filemgr isWritableFileAtPath:documentsDirectory] == YES){
    NSLog (@"File is readable and writable");
}

Upvotes: 1

Views: 9621

Answers (2)

Anton Tropashko
Anton Tropashko

Reputation: 5806

swift5

guard let docdir = NSSearchPathForDirectoriesInDomains(.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first else {
            preconditionFailure()
}
let path = (docdir as NSString).appendingPathComponent(yourfilename + "." + yourfilenameExtension)

Upvotes: 1

Dipen Panchasara
Dipen Panchasara

Reputation: 13600

//  Following Code will create Directory in DocumentsDirectory

NSString *docDir = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *dirName = [docDir stringByAppendingPathComponent:@"MyDir"];

BOOL isDir
NSFileManager *fm = [NSFileManager defaultManager];
if(![fm fileExistsAtPath:dirName isDirectory:&isDir])
{
    if([fm createDirectoryAtPath:dirName withIntermediateDirectories:YES attributes:nil error:nil])
        NSLog(@"Directory Created");
    else
        NSLog(@"Directory Creation Failed");
}
else
    NSLog(@"Directory Already Exist");

Upvotes: 6

Related Questions