Launching an Mac App with Objective-C/Cocoa

ぃ、小莉子 提交于 2019-11-26 17:39:35

问题


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];

回答1:


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];



回答2:


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];


来源:https://stackoverflow.com/questions/5048677/launching-an-mac-app-with-objective-c-cocoa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!