如何在App的小组容器中创建目录?
我已尝试用作文件管理器:
let directory: NSURL = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier("APP_GROUP_IDENTIFIER")!
但是没有创建目录...如何在此文件夹中创建目录?
答案 0 :(得分:11)
containerURLForSecurityApplicationGroupIdentifier
将URL返回到组容器
要创建目录,请将新目录名称附加为路径组件
let fileManager = NSFileManager.defaultManager()
if let directory = fileManager.containerURLForSecurityApplicationGroupIdentifier("APP_GROUP_IDENTIFIER") {
let newDirectory = directory.URLByAppendingPathComponent("MyDirectory")
try? fileManager.createDirectoryAtURL(newDirectory, withIntermediateDirectories: false, attributes: nil)
}
斯威夫特3:
let fileManager = FileManager.default
if let directory = fileManager.containerURL(forSecurityApplicationGroupIdentifier: "APP_GROUP_IDENTIFIER") {
let newDirectory = directory.appendingPathComponent("MyDirectory")
try? fileManager.createDirectory(at: newDirectory, withIntermediateDirectories: false, attributes: nil)
}
答案 1 :(得分:1)
选中启用"应用组" 权利。它可以从项目 - >启用能力 - >应用程序组 - >开启。
添加应用程序组标识" group.com.companyName.exampleApp" ,如上图所示。
现在,您可以使用指定的标识符访问应用程序组容器。
let appIdentifier = "group.com.companyName.exampleApp" let fileManager = NSFileManager.defaultManager() let container = fileManager.containerURLForSecurityApplicationGroupIdentifier(appIdentifier)
如果您正确设置了所有内容,您将在"容器"中获得一个URL地址。
现在,
do{ if let container = container {let directoryPath = container.URLByAppendingPathComponent("sampleDirectory") var isDir : ObjCBool = false if let path = directoryPath?.path where fileManager.fileExistsAtPath(path, isDirectory:&isDir) { if isDir { // file exists and is a directory } else { // file exists and is not a directory } } else if let directoryPath = directoryPath { // file or directory does not exist try fileManager.createDirectoryAtURL(directoryPath, withIntermediateDirectories: false, attributes: nil) } } } catch let error as NSError { print(error.description) }