假设您有一个应用程序的名称Mail.app
,您如何从应用程序名称以编程方式获取com.apple.mail
?
答案 0 :(得分:17)
以下方法将为命名应用程序返回应用程序的Bundle Identifier:
- (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;
}
对于Mail,你可以这样调用方法:
NSString * appID = [self bundleIdentifierForApplicationName:@"Mail"];
appID
现在包含com.apple.mail
答案 1 :(得分:1)
扩展Francesco Germinara在Swift 4中的回答,macOS 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
}
}
将它放在你的Swift项目中,你可以这样称呼它:
let id = Bundle.bundleIDFor(appNamed: "Mail.app")
或
let id = Bundle.bundleIDFor(appNamed: "Mail")
答案 2 :(得分:0)
它是Contents / Info.plist中键CFBundleIdentifier的值
答案 3 :(得分:0)
这是一种可能的快速实施
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 ""
}