8

In a macOS app, I'm using this code to create a directory in Application Support folder.

let directoryURL = appSupportURL.appendingPathComponent("com.myCompany.myApp").appendingPathComponent("Documents")

How can the string com.myCompany.myApp obtained programmatically in Swift?

I saw this question but I'm not sure how to use it in my macOS Swift app: Access App Identifier Prefix programmatically

ha100
  • 1,563
  • 1
  • 21
  • 28
Cue
  • 2,952
  • 3
  • 33
  • 54
  • 1
    If you sandbox your app, this is a non-problem. Your Application Support folder is yours alone. – matt May 30 '17 at 21:41

2 Answers2

15
if let bundleIdentifier = Bundle.main.bundleIdentifier {
    appSupportURL.appendingPathComponent("\(bundleIdentifier)").appendingPathComponent("Documents")
}

Little explanation: Property bundleIdentifier is optional, therefore you have to safely-unwrap the value and then you won't be asked for any exclamation mark :)

Dominik Bucher
  • 2,120
  • 2
  • 16
  • 25
1

It is pretty simple to get the app ID :

let bundleIdentifier =  Bundle.main.bundleIdentifier
  appSupportURL.appendingPathComponent("\(bundleIdentifier)").appendingPathComponent("Documents")

A bundle identifier is the string assigned to the CFBundleIdentifier key in the bundle’s Info.plist file. This string is typically formatted using reverse-DNS notation so as to prevent name space conflicts with developers in other companies. For example, a Finder plug-in from Apple might use the string com.apple.Finder.MyGetInfoPlugin as its bundle identifier. Rather than passing a pointer to a bundle object around your code, clients that need a reference to a bundle can simply use the bundle identifier to retrieve it

For more details & other operation's details, please check

https://developer.apple.com/library/content/documentation/CoreFoundation/Conceptual/CFBundles/AccessingaBundlesContents/AccessingaBundlesContents.html

Ash
  • 5,525
  • 1
  • 40
  • 34