cocoansbundle

How do you get the Bundle Identifier from an application's name in Cocoa?


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


Solution

  • The following method will return an application's Bundle Identifier for a 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 like so:

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

    appID now contains com.apple.mail

    Swift 5.1

    import AppKit
    
    func bundleIdentifier(forAppName appName: String) -> String? {
    
        let workspace = NSWorkspace.shared
        let appPath = workspace.fullPath(forApplication: appName)
        if let appPath = appPath {
            let appBundle = Bundle(path: appPath)
            return appBundle?.bundleIdentifier
        }
        return nil
    }
    
    // For Mail you can call the method like so:
    
    let appID = bundleIdentifier(forAppName: "Mail")
    

    Deprecation

    The fullPathForApplication: / fullPath(forApplication:) method has been deprecated in macOS 10.15 - it is unclear what the answer is going forward.