繁体   English   中英

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

[英]Launch OS X Application Programmatically

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

在OS X上执行此操作的首选方法是通过NSWorkspace类,该类提供了几种启动应用程序的方法。 其中之一, 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];

您可以使用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
         }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM