140

How can I get the bundle ID in Swift?

Objective-C version:

NSString *bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];
Shruti Thombre
  • 989
  • 4
  • 11
  • 27
User
  • 23,729
  • 38
  • 124
  • 207

3 Answers3

295

Try this:

let bundleID = NSBundle.mainBundle().bundleIdentifier

Swift 3+:

let bundleID = Bundle.main.bundleIdentifier
Gibolt
  • 42,564
  • 15
  • 187
  • 127
Sebastian
  • 6,154
  • 5
  • 33
  • 51
  • 29
    Do you know why `bundleIdentifier` is an optional? In what cases can it be `nil`? – Alexander Dec 31 '16 at 03:06
  • 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. – Sethmr Nov 03 '17 at 19:41
  • 7
    @Alexander when it is not the main bundle, or `CFBundleIdentifier` is missing – ArtFeel Nov 23 '18 at 15:51
  • @Alexander It’s nil for unbundled applications’ main bundles and applications whose info.plist files don’t have an entry for the identifier. – Andreas is moving to Codidact Apr 05 '23 at 15:06
  • 1
    @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 sharing – Alexander Apr 05 '23 at 15:40
13

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?
9

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

Ash
  • 5,525
  • 1
  • 40
  • 34