2011-03-01 135 views
9

我记得存在Cocoa框架或AppleScript字典来检查是否在计算机上的任何位置安装了具有特定名称的应用程序包。检查是否存在Mac OS X应用程序

我该怎么做?可可,AppleScript或命令行对我都有用。

回答

21

您应该使用Launch Services要做到这一点,尤其是功能LSFindApplicationForInfo()

您可以使用它,像这样:

#import <ApplicationServices/ApplicationServices.h> 

CFURLRef appURL = NULL; 
OSStatus result = LSFindApplicationForInfo (
            kLSUnknownCreator,   //creator codes are dead, so we don't care about it 
            CFSTR("com.apple.Safari"), //you can use the bundle ID here 
            NULL,      //or the name of the app here (CFSTR("Safari.app")) 
            NULL,      //this is used if you want an FSRef rather than a CFURLRef 
            &appURL 
            ); 
switch(result) 
{ 
    case noErr: 
     NSLog(@"the app's URL is: %@",appURL); 
     break; 
    case kLSApplicationNotFoundErr: 
     NSLog(@"app not found"); 
     break; 
    default: 
     NSLog(@"an error occurred: %d",result); 
     break;   
} 

//the CFURLRef returned from the function is retained as per the docs so we must release it 
if(appURL) 
    CFRelease(appURL); 
+1

不要忘记如果(appURL)在发布之前,万一没有找到,它会尝试释放一个不存在的对象,产生崩溃 – Daniel 2012-05-03 10:43:39

+0

好点,修复。 – 2012-05-04 02:34:22

+0

注意:从10.12开始,LSFindApplicationForInfo似乎不推荐使用。任何人都知道另一种选择 – Tony 2017-02-18 05:33:28

3

在命令行中,这似乎做到这一点:

> mdfind 'kMDItemContentType == "com.apple.application-bundle" && kMDItemFSName = "Google Chrome.app"' 
+3

使用Spotlight API查找应用程序将比使用启动服务慢得多。 – 2011-03-01 15:42:01

1

您还可以使用lsregister

on doesAppExist(appName) 
    if (do shell script "/System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/LaunchServices.framework/Versions/A/Support/lsregister -dump | grep com.apple.Safari") ¬ 
    contains "com.apple.Safari" then return true 
end appExists 

这很快,你可以很容易地从Python等其他语言。你会想玩弄你最喜欢的东西,让它变得最有效率。

+0

你说得对,它是不能使用本地API的语言的解决方案。然而,从Cocoa应用程序中调用命令行工具是件小事,因为它只是查询完全相同的Launch Services API。 – 2011-03-02 01:11:02

+0

确实如此,但OP并不清楚他是如何使用它的。另外其他人一定会发现这个页面的其他一些类似的问题。 – Clark 2011-03-02 02:39:22

相关问题