How to obtain the app ID programmatically in Swift?

Cue picture Cue · May 30, 2017 · Viewed 8.8k times · Source

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

Answer

Dominik Bucher picture Dominik Bucher · May 30, 2017
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 :)