我如何编程打开我正在构建的应用程序中包含的OS X App(.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:@"tryn
run application "Macintosh HD:Applications:_Sandbox-AppleScript0.app"n
on error number -609 # 'Connection is invalid' error that is spuriously reported # simply ignoren
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
}
}
}