首页 > 解决方案 > -[NSWorkspace openApplicationAtURL:configuration:completionHandler:] 在登录项中不起作用

问题描述

在我的 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;
}

有没有人有类似的问题?我对新方法做错了什么?

标签: macoscocoaappkitnsworkspace

解决方案


弄清楚了。登录项退出太快。它应该等待打开操作完成。就像是:

    [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];

推荐阅读