以编程方式启动 OS X 应用程序

Launch OS X Application Programmatically

如何以编程方式打开我正在构建的应用程序中包含的 OS X 应用程序 (.app)?

您可以使用 Apple 脚本。

NSDictionary* errorDict;
NSAppleEventDescriptor* returnDescriptor = NULL;

NSAppleScript* scriptObject;
scriptObject = [[NSAppleScript alloc] initWithSource:@"try\n
run application \"Macintosh HD:Applications:_Sandbox-AppleScript0.app\"\n
on error number -609 # 'Connection is invalid' error that is spuriously reported # simply ignore\n
end try"];

if (returnDescriptor != NULL) {
     // successful execution
     if (kAENullEvent != [returnDescriptor descriptorType]) {
         // script returned an AppleScript result
         if (cAEList == [returnDescriptor descriptorType]) {
             // result is a list of other descriptors
         }
         else {
              // coerce the result to the appropriate ObjC type
         }
    }
}

在 OS X 上执行此操作的首选方法是通过 NSWorkspace class,它提供了两种启动应用程序的方法。其中之一,launchApplicationAtURL:options:configuration:error: 允许您指定一个文件 URL 到要启动的应用程序。除了没有像 system() 和 Apple Event 解决方案这样的沙盒问题之外,它还为您提供了一种简单的方法来操纵应用程序的启动方式,例如。您可以指定要传递给应用程序的环境变量。

以下代码片段用于以编程方式启动应用程序:

NSString *path = [[[NSBundle mainBundle] bundlePath] stringByDeletingLastPathComponent];
path = [path stringByAppendingString:@"/MyApp.app"]; // App Path
NSWorkspace *ws=[NSWorkspace sharedWorkspace];
NSURL* url = [NSURL fileURLWithPath:path isDirectory:NO];
[ws launchApplicationAtURL:url
                           options:NSWorkspaceLaunchWithoutActivation
                     configuration:nil
                             error:nil];