如何在iOS应用程序的默认文档目录中创建文件

时间:2013-05-19 17:23:56

标签: ios objective-c

我正在编写一个需要在文件中存储一些持久性信息的应用程序,但我在调试createFileAtPath:contents:attributes:NSFileManager的函数时遇到问题,我已将问题减少到下面的代码段。

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");
    }
}

由于该函数没有采用NSError对象,因此我无法找到它返回false的原因。

从我在这里看到的其他例子Write a file on iOS和这里How to programmatically create an empty .m4a file of a certain length under iOS using CoreAudio on device?,可以将nil传递给内容和属性参数。我已经尝试指定两个参数并获得相同的结果。

我认为这可能是权限问题,但我不确定以下代码是否是检查目录权限的正确方法。

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

2 个答案:

答案 0 :(得分:6)

//  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");

答案 1 :(得分:0)

swift5

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