MacOsX:如何从“命令行工具”启动应用程序(.app)应用类型

问题描述:

在Xcode 4.6中,我基于命令行工具项目模板创建了一个新的应用程序。
如何以编程方式从命令行工具应用程序启动另一个应用程序(.app应用程序包)?

In Xcode 4.6, I created a new application based on the "Command Line Tool" project template. 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 launchAppWithBundleIdentifier:options:additionalEventParamDescriptor:launchIdentifier: 启动应用程序。如果你还不知道,你可以通过检查它的 AppName.app/Contents/Info.plist 文件来获取应用程序包的包标识符。然后使用以下代码:

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!);
}

重要: NSWorkspace AppKit.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.framework Cocoa.framework

这将导致所有3列在链接二进制文件中。此时,您可以从连接阶段中删除 Foundation.framework AppKit.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: