openApplicationAtURL function can't open cocoa application itself

I am using the openApplicationAtURL:(NSURL *)applicationURL configuration:(NSWorkspaceOpenConfiguration *)configuration completionHandler:(void (^ _Nullable)(NSRunningApplication *_Nullable app, NSError *_Nullable error))completionHandler function to open the application itself on macOS Ventura. I need to restart the software itself before it exits. So I call the openApplicationAtURL function to reopen it. But it failed. In the same code, I can successfully open any other software(As soon as I change the name of the software), but it can not open the software itself.

Is there any way to resolve it?

Sample code:

NSBundle* bundle = NSBundle.mainBundle;

NSWorkspace* workspace = NSWorkspace.sharedWorkspace;

NSWorkspaceOpenConfiguration* configuration = [NSWorkspaceOpenConfiguration new];

NSDictionary* env = @{};

[configuration setEnvironment: env];

[configuration setPromptsUserIfNeeded: YES];

NSString* path = bundle.bundlePath;

[workspace openApplicationAtURL: [NSURL fileURLWithPath: path] configuration: configuration completionHandler:^(NSRunningApplication* app, NSError* error) {

    if (error) {

        NSLog(@"Failed to run the app: %@", error.localizedDescription);

    }

}];

Accepted Reply

NSWorkspace will, by default, not open an new instance of an app. So, if you call it on yourself, it’s effectively a no-op [1]. Historically the solution here was to have a small helper tool that calls NSWorkspace to launch the app after a short delay. So:

  1. Main app starts helper tool process.

  2. Main app terminates.

  3. Helper tool process launches main app.

  4. Helper tool process terminates.

However, on modern systems you can avoid this dance by setting the createsNewApplicationInstance property.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

[1] Well, if your app isn’t at the front I think it’ll bring it to the front.

  • Great! It totally works, thank you!

Add a Comment

Replies

NSWorkspace will, by default, not open an new instance of an app. So, if you call it on yourself, it’s effectively a no-op [1]. Historically the solution here was to have a small helper tool that calls NSWorkspace to launch the app after a short delay. So:

  1. Main app starts helper tool process.

  2. Main app terminates.

  3. Helper tool process launches main app.

  4. Helper tool process terminates.

However, on modern systems you can avoid this dance by setting the createsNewApplicationInstance property.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

[1] Well, if your app isn’t at the front I think it’ll bring it to the front.

  • Great! It totally works, thank you!

Add a Comment