Launch OS X Application Programmatically

How do I programmatically open an OS X app (.app) that is contained in an app I am building?


source to share

3 answers

The preferred way to do this in OS X is through a class NSWorkspace

that provides several methods for launching applications. One of them launchApplicationAtURL:options:configuration:error:

allows you to specify the URL of the file to launch the application. Besides not having sandbox issues like the solution system()

and Apple Event, it also gives you an easy way to control the launch of your application, for example. you can specify environment variables to be passed to the application.



The following piece of code is used to run the application programmatically:

NSString *path = [[[NSBundle mainBundle] bundlePath] stringByDeletingLastPathComponent];
path = [path stringByAppendingString:@"/"]; // App Path
NSWorkspace *ws=[NSWorkspace sharedWorkspace];
NSURL* url = [NSURL fileURLWithPath:path isDirectory:NO];
[ws launchApplicationAtURL:url




You can use Apple Script.

NSDictionary* errorDict;
NSAppleEventDescriptor* returnDescriptor = NULL;

NSAppleScript* scriptObject;
scriptObject = [[NSAppleScript alloc] initWithSource:@"try\n
run application \"Macintosh\"\n
on error number -609 # 'Connection is invalid' error that is spuriously reported # simply ignore\n
end try"];

if (returnDescriptor != NULL) {
     // successful execution
     if (kAENullEvent != [returnDescriptor descriptorType]) {
         // script returned an AppleScript result
         if (cAEList == [returnDescriptor descriptorType]) {
             // result is a list of other descriptors
         else {
              // coerce the result to the appropriate ObjC type




All Articles