检查是否存在Mac OS X应用程序

9

我记得有一个Cocoa框架或者AppleScript字典可以检查计算机上是否安装了指定名称的应用程序包,不管它在哪个位置。

我该如何操作呢?对我来说,无论是Cocoa、AppleScript还是命令行都很有用。

4个回答

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
在发布之前不要忘记加上if(appURL)判断,以防找不到对象而尝试释放不存在的对象,导致崩溃。 - Daniel
注意:LSFindApplicationForInfo 在 10.12 版本已被弃用。有没有其他替代方案? - Anton Strogonoff

3

从命令行看,这似乎可以做到:

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

3
使用 Spotlight API 查找应用程序比使用 Launch Services 更慢。 - Rob Keniger

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 进行操作。你需要尝试一下,优化 grep 的功能以获得最高效的结果。


你说得对,这是为不能使用本地API的语言提供的解决方案。然而,从Cocoa应用程序调用命令行工具会过度杀伤力,因为它只是查询相同的Launch Services API。 - Rob Keniger
真的,但是原帖并没有清楚地说明他如何使用它。此外,其他人肯定会在某些类似的问题上找到这个页面。 - Clark

0

像这样快速简单:

appInstalled("com.apple.Safari") --> true
appInstalled("com.api.finder") --> false
appInstalled("com.apple.finder") --> true
appInstalled("org.m0k.transmission") --> true, on my Mac, Transmission.app
appInstalled("org.videolan.vlc") --> true, on my Mac, VLC.app
appInstalled("com.apple.Music") --> true, on my Mac, Music.app
appInstalled("com.apple.iTunes") --> false, on my Mac, iTunes.app

on appInstalled(bundleID)
    try
        application id bundleID
        return true
    end try
    return false
end appInstalled

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接