在 iOS 应用程序的文档文件夹中创建一个文件夹

我只是想在我的 iPhone 应用程序的文档文件夹中创建新的文件夹。

有人知道怎么做吗?

感谢你的帮助!

110964 次浏览

我是这么做的:

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

我不喜欢“[ path objectAtIndex: 0]”,因为如果苹果添加了一个以“ 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

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

Http://developer.apple.com/library/ios/documentation/iphone/conceptual/iphoneosprogrammingguide/standardbehaviors/standardbehaviors.html#//apple_ref/doc/uid/tp40007072-ch4-sw6

因为 NSSearchPathForDirectoriesInDomain 功能最初是为了 Mac OS X,那里可能有更多 而不是这些目录中的任何一个, 它返回一个路径数组 而不是单一的路径。在 iOS 系统中, 结果数组应该包含 目录的单个路径 3-1显示了这种方法的典型用法 功能。

清单3-1获取到 应用程序的文档目录

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

这对我来说没问题,

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

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

-(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/Document/MyFolder

Swift 1.2和 iOS 8

在 document 目录中创建自定义目录(name = “ 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...")
}


}

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


}

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

Swift 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)
}