2011-03-01 134 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

相關問題