3

I have a Cocoa application (.app) and I would like to launch it from another Cocoa application, no problem here, but is there any way to launch the second application passing it some parameters ? maybe using the argv[] array in the main function?

willyMon
  • 612
  • 8
  • 19

2 Answers2

3

I did this using NSWorkspace to launch the app, and NSDistributedNotificationCenter to pass the data. This obviously isn't fully developed, but it worked. One caveat from the docs -- the dictionary I sent with the argument (just a string in this example) can't be used in a sandboxed app (the dictionary must be nil).

This is in the app that opens the other app:

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification 
{
ws = [NSWorkspace sharedWorkspace];
NSNotificationCenter *center = [ws notificationCenter];
[center addObserver:self selector:@selector(poster:) name:NSWorkspaceDidLaunchApplicationNotification object:nil];
[ws launchApplication:@"OtherApp.app"];
}

-(void)poster:(NSNotification *) aNote 
 {
NSDistributedNotificationCenter *center = [NSDistributedNotificationCenter defaultCenter];
NSDictionary *dict = [NSDictionary dictionaryWithObject:@"theDataToSend" forKey:@"startup"];
[center postNotificationName:@"launchWithData" object:nil userInfo:dict];
NSLog(@"Posted notification");
 }

And this is in the app that is opened:

-(void)awakeFromNib 
{
NSDistributedNotificationCenter *center = [NSDistributedNotificationCenter defaultCenter];
[center addObserver:self selector:@selector(doStartup:) name:@"launchWithData" object:nil];
}

 -(void)doStartup:(NSNotification *) aNote 
    {
    NSLog(@"%@",aNote.userInfo);
    }
Sangram Shivankar
  • 3,535
  • 3
  • 26
  • 38
rdelmar
  • 103,982
  • 12
  • 207
  • 218
  • Note that it is trivial to spoof a distributed notification. Any process can post one, with any data. Don't rely on them for anything secure. – Kurt Revis Mar 25 '12 at 21:17
  • Thanks for that info Kurt. What do you suggest for a more secure way to do this? – rdelmar Mar 25 '12 at 21:21
  • Unfortunately, it's not an easy problem to solve. Nothing else is nearly so convenient. Try UNIX domain sockets or a named pipe maybe. XPC if you can require 10.7. You'll still have to ensure that the other app talking to you is who you think it is -- there's not really any way around that. – Kurt Revis Mar 25 '12 at 21:34
  • Great work, just a question,in a sandbox application how to proceed? – willyMon Mar 29 '12 at 16:37
1

How are you launching the second Cocoa app?

When I've done this, I usually communicate with the other app using AppleScript via NSAppleScript. You can launch apps that way too. Of course, the other app has to support AppleScript.

You could also use Distributed Objects if you have control over both apps, but it is more complex.

If you ever have to work with a command-line program, then NSTask is useful.

louielouie
  • 14,881
  • 3
  • 26
  • 31