5

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.

Community
  • 1
  • 1
Yuxiao Zeng
  • 121
  • 2
  • 5

1 Answers1

3

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];
estobbart
  • 1,137
  • 12
  • 28
  • Yes, using `NSTask` to open `open(1)` will always work. I just wonder what is the method used by `open(1)`. – Yuxiao Zeng Oct 21 '12 at 04:05
  • I plugged this code into an app and gave it the full path of an mp4 from itunes and it worked. Can you try some other content? – estobbart Oct 21 '12 at 11:59
  • Well, I mean, I am curious about how `/usr/bin/open` is written, what classes and functions it uses, but not about how to use this tool. – Yuxiao Zeng Oct 21 '12 at 12:36
  • @Pink Not sure of open's internals. But your original problem was playing a Quicktime movie from a Cocoa app. If this wasn't a solution then what sort of problem are you trying to solve? – estobbart Oct 22 '12 at 15:40