在app group container swift中创建目录

时间:2016-02-21 20:41:32

标签: ios swift

如何在App的小组容器中创建目录?

我已尝试用作文件管理器:

let directory: NSURL = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier("APP_GROUP_IDENTIFIER")!

但是没有创建目录...如何在此文件夹中创建目录?

2 个答案:

答案 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)

  1. 选中启用"应用组" 权利。它可以从项目 - >启用能力 - >应用程序组 - >开启enter image description here

  2. 添加应用程序组标识" group.com.companyName.exampleApp" ,如上图所示。

  3. 现在,您可以使用指定的标识符访问应用程序组容器。

    let appIdentifier = "group.com.companyName.exampleApp"
    let fileManager = NSFileManager.defaultManager()
    let container = fileManager.containerURLForSecurityApplicationGroupIdentifier(appIdentifier)
    
  4. 如果您正确设置了所有内容,您将在"容器"中获得一个URL地址。

  5. 现在,

    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)
    }
    
  6. 礼貌:文件&目录检查代码取自https://stackoverflow.com/a/24696209/2666902