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?
Check you enable "App Group" entitlement. It can be enable from project -> Capabilities -> App Group -> switch on.
Add an app group identifier "group.com.companyName.exampleApp" as above image.
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)
If you set everything properly, you will get an URL address in "container".
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
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With