How do you get the Bundle ID on behalf of the application in Cocoa?

Say you have the name of the application, Mail.app , how do you programmatically get com.apple.mail from the name of the application?

+4
source share
4 answers

The following method returns the bundle package identifier for the named application:

 - (NSString *) bundleIdentifierForApplicationName:(NSString *)appName { NSWorkspace * workspace = [NSWorkspace sharedWorkspace]; NSString * appPath = [workspace fullPathForApplication:appName]; if (appPath) { NSBundle * appBundle = [NSBundle bundleWithPath:appPath]; return [appBundle bundleIdentifier]; } return nil; } 

For Mail, you can call the method as follows:

 NSString * appID = [self bundleIdentifierForApplicationName:@"Mail"]; 

appID now contains com.apple.mail

+16
source

This value is for the CFBundleIdentifier key in / Info.plist

0
source

This is a possible quick implementation.

 func bundleIdentifierForApplicationName(appName : String) -> String { var workspace = NSWorkspace.sharedWorkspace() var appPath : String = workspace.fullPathForApplication(appName) if (appPath != "") { var appBundle : NSBundle = NSBundle(path:appPath) return appBundle.bundleIdentifier } return "" } 
0
source

Extension on Francesco Germinara's answer, in Swift 4, MacOSX 10.13.2:

 extension Bundle { class func bundleIDFor(appNamed appName: String) -> String? { if let appPath = NSWorkspace.shared.fullPath(forApplication: appName) { if let itsBundle = Bundle(path: appPath) { // < in my build this condition fails if we're looking for the ID of the app we're running... if let itsID = itsBundle.bundleIdentifier { return itsID } } else { //Attempt to get the current running app. //This is probably too simplistic a catch for every single possibility if let ownID = Bundle.main.bundleIdentifier { return ownID } } } return nil } } 

By placing it in your Swift project, you can call it like this:

 let id = Bundle.bundleIDFor(appNamed: "Mail.app") 

or

 let id = Bundle.bundleIDFor(appNamed: "Mail") 
0
source

Source: https://habr.com/ru/post/1397963/


All Articles