Obtain bundle identifier programmatically in Swift?
Asked Answered
R

3

146

How can I get the bundle ID in Swift?

Objective-C version:

NSString *bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];
Rosalindarosalinde answered 17/9, 2014 at 17:46 Comment(0)
M
304

Try this:

let bundleID = NSBundle.mainBundle().bundleIdentifier

Swift 3+:

let bundleID = Bundle.main.bundleIdentifier
Megaera answered 17/9, 2014 at 17:53 Comment(5)
Do you know why bundleIdentifier is an optional? In what cases can it be nil?Nobody
Sometimes it isn't about in what cases it could be nil when it reaches the high level development, but about which cases it could be nil under the hood.String
@Nobody when it is not the main bundle, or CFBundleIdentifier is missingFloridafloridia
@Nobody It’s nil for unbundled applications’ main bundles and applications whose info.plist files don’t have an entry for the identifier.Ierna
@Andreasdetestscensorship Boy I wrote that 7 years ago, wild how the time passes by. I've since run into both of those case (typo in the Info.plist key name, and unbundled executables). Makes sense! Thanks for sharingNobody
H
14

It's pretty much the same thing in Swift except the class and method names have been shortened:

let bundleIdentifier = Bundle.main.bundleIdentifier // return type is String?
Hokum answered 17/9, 2014 at 17:54 Comment(0)
W
10

If you are trying to get it programmatically , you can use below line of code :

Objective-C:

NSString *bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];

Swift 3.0:

let bundleIdentifier =  Bundle.main.bundleIdentifier

Updated for latest swift It will work for both iOS and Mac apps.

For More Info, Check here :

Apple Docs: https://developer.apple.com/documentation/foundation/bundle#//apple_ref/occ/instm/NSBundle/bundleIdentifier

Weakwilled answered 8/9, 2016 at 21:44 Comment(1)
hey check for swift3, remove your negative check.Weakwilled

© 2022 - 2024 — McMap. All rights reserved.