Mac OS X: How to launch an application (.app) from

2020-06-29 02:55发布

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?

2条回答
ゆ 、 Hurt°
2楼-- · 2020-06-29 03:11

There are numerous ways to accomplish this, using Launch Services and or 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!);
}

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.

enter image description here

Add both AppKit.framework and 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:

enter image description here

查看更多
霸刀☆藐视天下
3楼-- · 2020-06-29 03:20

Have you tried "open"? At least in terminal "open" runs files and/or apps.

查看更多
登录 后发表回答