8

When launching Path Finder app with command line, I use open -a Path Finder.app /Users/. Based on this idea, I use the following code to launch Path Finder.

Can I have launch app without using open command line?

NSTask *task;
task = [[NSTask alloc] init];
[task setLaunchPath: @"/usr/bin/open"];

NSArray *arguments;
arguments = [NSArray arrayWithObjects: @"-a", @"Path Finder.app", @"/Users/", nil];
[task setArguments: arguments];

NSPipe *pipe;
pipe = [NSPipe pipe];
[task setStandardOutput: pipe];

NSFileHandle *file;
file = [pipe fileHandleForReading];

[task launch];
prosseek
  • 182,215
  • 215
  • 566
  • 871

2 Answers2

28
if(![[NSWorkspace sharedWorkspace] launchApplication:@"Path Finder"])
    NSLog(@"Path Finder failed to launch");

With Parameters:

NSWorkspace *workspace = [NSWorkspace sharedWorkspace];
NSURL *url = [NSURL fileURLWithPath:[workspace fullPathForApplication:@"Path Finder"]];
//Handle url==nil
NSError *error = nil;
NSArray *arguments = [NSArray arrayWithObjects:@"Argument1", @"Argument2", nil];
[workspace launchApplicationAtURL:url options:0 configuration:[NSDictionary dictionaryWithObject:arguments forKey:NSWorkspaceLaunchConfigurationArguments] error:&error];
//Handle error

You could also use NSTask to pass arguments:

NSTask *task = [[NSTask alloc] init];
NSBundle *bundle = [NSBundle bundleWithPath:[[NSWorkspace sharedWorkspace] fullPathForApplication:@"Path Finder"]]];
[task setLaunchPath:[bundle executablePath]];
NSArray *arguments = [NSArray arrayWithObjects:@"Argument1", @"Argument2", nil];
[task setArguments:arguments];
[task launch];
Brian
  • 15,599
  • 4
  • 46
  • 63
ughoavgfhw
  • 39,734
  • 6
  • 101
  • 123
  • 1
    You will need to use launchApplicationAtURL:options:configuration:error: to do that. I will add an example using that to my post. – ughoavgfhw Feb 19 '11 at 06:03
  • Well, I'm not sure, but in terms of brevity, my answer (using openFile: withApplication:) seems better (easier to understand and shorter). – prosseek Feb 19 '11 at 07:21
  • How do I access the configuration dictionary in the opened app? – rocky Sep 17 '13 at 00:19
  • 2
    @rocky You cannot directly access the dictionary, but the arguments stored in the dictionary will be passed as command line arguments, so you can use `argc` and `argv` in your main function. – ughoavgfhw Sep 18 '13 at 02:48
  • @ughoavgfhw which one will be fast? – PR Singh Feb 12 '18 at 07:06
3

Based on yuji's answer in different posting, NSWorkspace is the tool to use, and I could get the same result with only two lines of code.

The openFile can be used for passing the parameter to Path Finder, which is normally the directory, not a file. However, it works fine.

[[NSWorkspace sharedWorkspace] openFile:string2 withApplication:@"Path Finder"];
[[NSApplication sharedApplication] terminate:nil];
Community
  • 1
  • 1
prosseek
  • 182,215
  • 215
  • 566
  • 871