Mac OS X:如何从“命令行工具"启动应用程序(.app).应用类型? [英] Mac OS X: How to launch an application (.app) from a "Command Line Tool" type of app?

查看:230
本文介绍了Mac OS X:如何从“命令行工具"启动应用程序(.app).应用类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Xcode 4.6中,我基于命令行工具"项目模板创建了一个新应用程序.

In Xcode 4.6, I created a new application based on the "Command Line Tool" project template.

如何从该命令行工具"应用程序中以编程方式启动另一个应用程序(.app应用程序包)?

How can I programmatically start another application (.app application bundle) from that "Command Line Tool" app?

推荐答案

使用Launch Services和NSWorkspace有很多方法可以完成此任务.

There are numerous ways to accomplish this, using Launch Services and or NSWorkspace.

标识捆绑应用程序的一种更灵活的方法是通过其捆绑标识符(CFBundleIdentifier),捆绑标识符是类似于com.apple.TextEdit的字符串.这使您可以识别应用程序,而不必硬编码将找到该应用程序的假定路径,也无需硬编码应用程序捆绑包的名称,而这两种用户都可以轻松更改.您可以使用NSWorkspace

One of the more flexible ways to identity a bundled application is via its bundle identifier (CFBundleIdentifier), which is a string like com.apple.TextEdit. This allows you to identify an application without having to hard-code an assumed path where the application will be found, or by hard-coding the name of the application bundle, both of which a user could easily change. You can use NSWorkspace's launchAppWithBundleIdentifier:options:additionalEventParamDescriptor:launchIdentifier: to launch the app. If you don't already know it, you can obtain the bundle identifier of an application bundle by checking its AppName.app/Contents/Info.plist file. Then use the following code:

if (![[NSWorkspace sharedWorkspace]
       launchAppWithBundleIdentifier:@"com.apple.TextEdit"
                             options:NSWorkspaceLaunchDefault
      additionalEventParamDescriptor:NULL
                    launchIdentifier:NULL]) {
      NSLog(@"launching app failed!);
}

重要提示:NSWorkspaceAppKit.framework框架的一部分,该框架最初并未包含在命令行工具"项目模板中.要将其添加到您的项目中,请在目标列表中选择目标,如下图所示,然后单击+按钮以添加其他框架.

Important: NSWorkspace is part of the AppKit.framework framework, which is not initially included in the "Command Line Tool" project template. To add it to your project, select the target in the list of targets like shown in the image below, and click the + button to add additional frameworks.

同时添加AppKit.frameworkCocoa.framework.

这将导致所有3个文件都在与库链接二进制文件"步骤中列出.此时,您可以从链接阶段删除Foundation.frameworkAppKit.framework,而仅保留Cocoa.framework,如下所示:

That will result in all 3 being listed in the Link Binary With Libraries step. At that point, you can remove both the Foundation.framework and AppKit.framework from the linking stage, and leave just the Cocoa.framework, like below:

这篇关于Mac OS X:如何从“命令行工具"启动应用程序(.app).应用类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆