在iOS应用中的documents文件夹内创建一个文件夹


Answers:


326

我通过以下方式进行操作:

NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"/MyFolder"];

if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
    [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]; //Create folder

1
感谢您的答复,它可以工作,但是会在应用程序的文档文件夹旁边创建文件夹“ MyFolder” ..不在其内部。不知道为什么竟然
迈纳·米克尔

3
抱歉-那里是一个错字-必须在文档路径后附加@“ / MyFolder”,而不是@“ MyFolder”。
弗拉基米尔·

2
您可能需要将第三行更改为NSString * dataPath = [documentsDirectory stringByAppendingString:@“ / MyFolder”]; 因为NSSearchPathForDirectoriesInDomains不返回尾部斜杠。
Andreas

13
我修复了代码以使用更正确的“ stringByAppendingPathComponent”,无论输入字符串是否带有“ /”,它都可以正确执行操作。
Kendall Helmstetter Gelner,2009年

对我有很大帮助。.感谢弗拉基米尔
凯茜

14

我没有足够的声誉来评论Manni的答案,但是[paths objectAtIndex:0]是获取应用程序文档目录的标准方法

http://developer.apple.com/library/ios/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/StandardBehaviors/StandardBehaviors.html#//apple_ref/doc/uid/TP40007072-CH4-SW6

由于NSSearchPathForDirectoriesInDomains函数最初是为Mac OS X设计的,因此每个目录中可能有多个目录,因此它返回路径数组,而不是单个路径。在iOS中,结果数组应包含目录的单个路径。清单3-1显示了此函数的典型用法。

清单3-1获取应用程序的Documents目录的路径

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

1
我认为检索文档目录路径的最简单方法是:NSString* path = [@"~/Documents" stringByExpandingTildeInPath];
S1LENT WARRIOR 2014年

14

Swift 3解决方案:

private func createImagesFolder() {
        // path to documents directory
        let documentDirectoryPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first
        if let documentDirectoryPath = documentDirectoryPath {
            // create the custom folder path
            let imagesDirectoryPath = documentDirectoryPath.appending("/images")
            let fileManager = FileManager.default
            if !fileManager.fileExists(atPath: imagesDirectoryPath) {
                do {
                    try fileManager.createDirectory(atPath: imagesDirectoryPath,
                                                    withIntermediateDirectories: false,
                                                    attributes: nil)
                } catch {
                    print("Error creating images folder in documents dir: \(error)")
                }
            }
        }
    }

9

我不喜欢“ [paths objectAtIndex:0]”,因为如果Apple添加以“ A”,“ B”或“ C”开头的新文件夹,则“文档”文件夹不是目录中的第一个文件夹。

更好:

NSString *dataPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/MyFolder"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
    [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]; //Create folder

8
参见蒂姆的答案。使用NSSearchPathForDirectoryiesInDomains是检索用户Documents目录的标准方法。
Tim Swast

1
如果Apple决定将Documents目录重命名为“ MyDocuments”(或类似名称),则您的方法也将不起作用。
Mehlyfication 2014年

8

夫特2溶液:

let documentDirectoryPath: String = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first!
if !NSFileManager.defaultManager().fileExistsAtPath(documentDirectoryPath) {
        do {
            try NSFileManager.defaultManager().createDirectoryAtPath(documentDirectoryPath, withIntermediateDirectories: false, attributes: nil)

        } catch let createDirectoryError as NSError {
            print("Error with creating directory at path: \(createDirectoryError.localizedDescription)")
        }

    }

5

这对我来说很好

NSFileManager *fm = [NSFileManager defaultManager];
NSArray *appSupportDir = [fm URLsForDirectory:NSDocumentsDirectory inDomains:NSUserDomainMask];
NSURL* dirPath = [[appSupportDir objectAtIndex:0] URLByAppendingPathComponent:@"YourFolderName"];

NSError*    theError = nil; //error setting
if (![fm createDirectoryAtURL:dirPath withIntermediateDirectories:YES
                           attributes:nil error:&theError])
{
   NSLog(@"not created");
}

它应该是NSDocumentDirectory代替NSDocumentsDirectory
普拉迪普·雷迪Kypa

3

迅捷4.0

let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
// Get documents folder
let documentsDirectory: String = paths.first ?? ""
// Get your folder path
let dataPath = documentsDirectory + "/yourFolderName"
if !FileManager.default.fileExists(atPath: dataPath) {
    // Creates that folder if not exists
    try? FileManager.default.createDirectory(atPath: dataPath, withIntermediateDirectories: false, attributes: nil)
}

如何将数据写入新创建的目录?
Logger

1

以下代码可能有助于创建目录:

-(void) createDirectory : (NSString *) dirName {

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Fetch path for document directory
dataPath = (NSMutableString *)[documentsDirectory stringByAppendingPathComponent:dirName];

NSError *error;

if (![[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]) {
    NSLog(@"Couldn't create directory error: %@", error);
}
else {
    NSLog(@"directory created!");
}

NSLog(@"dataPath : %@ ",dataPath); // Path of folder created

}

用法:

[self createDirectory:@"MyFolder"];

结果:

目录已创建!

dataPath:/ var / mobile / Applications / BD4B5566-1F11-4723-B54C-F1D0B23CBC / Documents / MyFolder


1

Swift 1.2和iOS 8

在文件目录内创建自定义目录(名称=“ MyCustomData”),但前提是该目录不存在。

// path to documents directory
let documentDirectoryPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first as! String

// create the custom folder path
let myCustomDataDirectoryPath = documentDirectoryPath.stringByAppendingPathComponent("/MyCustomData")

// check if directory does not exist
if NSFileManager.defaultManager().fileExistsAtPath(myCustomDataDirectoryPath) == false {

    // create the directory
    var createDirectoryError: NSError? = nil
    NSFileManager.defaultManager().createDirectoryAtPath(myCustomDataDirectoryPath, withIntermediateDirectories: false, attributes: nil, error: &createDirectoryError)

    // handle the error, you may call an exception
    if createDirectoryError != nil {
        println("Handle directory creation error...")
    }

}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.