【问题标题】:Check if a Mac OS X application is present检查是否存在 Mac OS X 应用程序
【发布时间】:2011-07-06 13:06:41
【问题描述】:

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

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

【问题讨论】:

    标签: cocoa macos applescript


    【解决方案1】:

    您应该使用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);
    

    【讨论】:

    • 释放前不要忘记if(appURL),万一找不到它会尝试释放一个不存在的对象,导致崩溃
    • 注意:从 10.12 开始,LSFindApplicationForInfo 似乎已被弃用。有人知道替代方案吗?
    【解决方案2】:

    从命令行看来是这样的:

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

    【讨论】:

    • 使用 Spotlight API 查找应用程序将比使用启动服务慢得多。
    【解决方案3】:

    您也可以使用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 应用程序调用命令行工具将是多余的,因为它只查询相同的启动服务 API。
    • 是的,但 OP 并不清楚他是如何使用它的。另外,其他人肯定会找到此页面来解决其他类似问题。
    猜你喜欢
    • 1970-01-01
    • 2013-05-12
    • 2012-01-13
    • 2013-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多