Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create directory in app group container swift

Tags:

ios

swift

How can I go about creating a directory in my App's group container?

I've tried using as the file manager:

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

but that doesn't create a directory...How can I go about creating a directory in this folder?

like image 741
user3076658 Avatar asked Feb 21 '16 20:02

user3076658


2 Answers

  1. Check you enable "App Group" entitlement. It can be enable from project -> Capabilities -> App Group -> switch on.enter image description here

  2. Add an app group identifier "group.com.companyName.exampleApp" as above image.

  3. Now you can access app group container using the specified identifier.

    let appIdentifier = "group.com.companyName.exampleApp"
    let fileManager = NSFileManager.defaultManager()
    let container = fileManager.containerURLForSecurityApplicationGroupIdentifier(appIdentifier)
    
  4. If you set everything properly, you will get an URL address in "container".

  5. Now,

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

courtesy: file & directory checking code taken from https://stackoverflow.com/a/24696209/2666902

like image 179
Milan Kamilya Avatar answered Oct 26 '22 19:10

Milan Kamilya


containerURLForSecurityApplicationGroupIdentifier returns the URL to the group container.
To create a directory append the new directory name as path component

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

Swift 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)
}
like image 25
vadian Avatar answered Oct 26 '22 19:10

vadian