Search code examples
objective-cmacosqtcocoa

How to open file with a specific Application Bundle?


I wrote an application in Qt for macOS & Windows. Now we want to communicate with that app from the browser using custom protocols. As it seems not possible to add this to Qt I tried to build a Cocoa helper app that just receives the message created in the browser from macOS using a custom protocol. That so far works and was simple.

But I can't manage to get it to open a document in my (separate Qt) application.

Trial 1:

void launchApplicationBundleWithArguments(NSString *bundleIdentifier, NSString *executablePath, NSArray<NSString *> *arguments) 
{
    NSWorkspace *workspace = [NSWorkspace sharedWorkspace];
    NSURL *url = [workspace URLForApplicationWithBundleIdentifier:bundleIdentifier];
    
    if (url) {
        NSError *error = nil;
        
        NSDictionary *configuration = @{NSWorkspaceLaunchConfigurationArguments: launchArguments};
      
        if (![workspace launchApplicationAtURL:url options:NSWorkspaceLaunchDefault configuration:configuration error:&error]) {
            NSLog(@"Error launching application: %@", error);
        }   
    } else {
        NSLog(@"Application bundle with identifier %@ not found", bundleIdentifier);
    }
}

This launches my application, but won't send the file's path (stored in arguments) to the command line of my main application. No error is reported.

Trial 2:

NSWorkspaceOpenConfiguration* configuration = [NSWorkspaceOpenConfiguration new];
[configuration setArguments: launchArguments];
 [configuration setPromptsUserIfNeeded: YES];
 [workspace openApplicationAtURL: [NSURL fileURLWithPath: executablePath] configuration: configuration completionHandler:^(NSRunningApplication* app, NSError* error) {
   if (error) {
     NSLog(@"Failed to run the app: %@", error.localizedDescription);
   }
 }];

This fails with a message box saying that my helper application does not have sufficient access rights to start the other application.

How can this be done?


Solution

  • According to the documentation of the arguments property of the NSWorkspaceOpenConfiguration class, a sandboxed app cannot pass arguments to another app that it is launching. So make sure that your helper application is not sandboxed.