Yuxiao Zeng
Yuxiao Zeng

Reputation: 141

Cocoa code for launching an app with parameters

I want a Cocoa equivalent of the command line tool open(1), especially for the usage in this form:

open -a <SomeApplication> <SomeFile> --args <Arg1> <Arg2> ...

Take QuickTime as an example. The following command line will open a file using QuickTime, and the arguments can control if QuickTime plays the file on startup.

open -a "QuickTime Player" a.mp4 --args -MGPlayMovieOnOpen 0 # or 1

I have read Launching an Mac App with Objective-C/Cocoa. prosseek's answer, which I think is equivalent to open -a <App> <File>, works well when I do not specify any argument. ughoavgfhw's answer, which I think is equivalent to open -a <App> --args <Arg1> <Arg2> ..., works well when I do not specify any file to open. But neither can specify a filename and arguments at the same time.

I have also tried to append the filename to the argument list, which is the common way used by unix programs. It seems that some applications can accept it, but some cannot. QuickTime prompts an error saying it cannot open the file. I am using the following code.

NSWorkspace *workspace = [NSWorkspace sharedWorkspace];
NSURL *url = [NSURL fileURLWithPath:[workspace fullPathForApplication:@"QuickTime Player"]];
NSArray *arguments = [NSArray arrayWithObjects:@"-MGPlayMovieOnOpen", @"0", @"a.mp4", nil];
[workspace launchApplicationAtURL:url options:0 configuration:[NSDictionary dictionaryWithObject:arguments forKey:NSWorkspaceLaunchConfigurationArguments] error:nil];
// open -a "QuickTime Player" --args -MGPlayMovieOnOpen 0 a.mp4

It seems that the mechanism in opening files differs from usual arguments. Can anyone explain the internals of open(1), or just give me a solution? Thanks.

Upvotes: 5

Views: 2693

Answers (1)

estobbart
estobbart

Reputation: 1145

You might want to pipe the output of the task so you know the results. "a.mp4" needs to be the full path to the file.

NSArray *args = [NSArray arrayWithObjects:@"-a", @"QuickTime Player", @"--args", @"a.mp4", nil];
NSTask *task = [NSTask new];
[task setLaunchPath:@"/usr/bin/open"];
[task setArguments:args];

[task launch];

Upvotes: 3

Related Questions