在我的MacOS应用程序中,有一个登录项使用-[NSWorkspace launchApplicationAtURL:options:configuration:error:]
方法启动主应用程序。它工作得很好,但这种方法现在被弃用,取而代之的是-[NSWorkspace openApplicationAtURL:configuration:completionHandler:]
。当我尝试使用后者时,什么也没发生。没有启动任何应用程序,也没有报告任何错误。这是省略了小细节的原始代码。
int main() {
@autoreleasepool {
NSBundle* bundle = NSBundle.mainBundle;
NSWorkspace* workspace = NSWorkspace.sharedWorkspace;
NSString* path = bundle.bundlePath;
for (int i = 0; i < 4; ++i) {
path = [path stringByDeletingLastPathComponent];
}
NSDictionary* env = @{
// ...
};
#if 1 /* switch between new and old method versions */
NSWorkspaceOpenConfiguration* configuration = [NSWorkspaceOpenConfiguration new];
[configuration setEnvironment: env];
[configuration setPromptsUserIfNeeded: YES];
[workspace openApplicationAtURL: [NSURL fileURLWithPath: path] configuration: configuration completionHandler:^(NSRunningApplication* app, NSError* error) {
if (error) {
NSLog(@"Failed to run the app: %@", error.localizedDescription);
}
}];
#else
NSDictionary* configuration = @{ NSWorkspaceLaunchConfigurationEnvironment: env };
NSError* error = nil;
[workspace launchApplicationAtURL: [NSURL fileURLWithPath: path]
options: NSWorkspaceLaunchDefault
configuration: configuration
error: &error];
if (error) {
NSLog(@"Failed to run the app: %@", error.localizedDescription);
}
#endif
}
return 0;
}
有人有类似的问题吗?我用新方法做错了什么?
想明白了。登录项目退出得太早。它应该等待打开操作完成。类似于:
[workspace openApplicationAtURL: [NSURL fileURLWithPath: path] configuration: configuration completionHandler:^(NSRunningApplication* app, NSError* error) {
if (error) {
NSLog(@"Failed to run the app: %@", error.localizedDescription);
}
exit(0);
}];
[NSThread sleepForTimeInterval: 10];