Launch OS X Application Programmatically

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

+3


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.



+4


source


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



NSString *path = [[[NSBundle mainBundle] bundlePath] stringByDeletingLastPathComponent];
path = [path stringByAppendingString:@"/MyApp.app"]; // App Path
NSWorkspace *ws=[NSWorkspace sharedWorkspace];
NSURL* url = [NSURL fileURLWithPath:path isDirectory:NO];
[ws launchApplicationAtURL:url
                           options:NSWorkspaceLaunchWithoutActivation
                     configuration:nil
                             error:nil];

      

+1


source


You can use Apple Script.

NSDictionary* errorDict;
NSAppleEventDescriptor* returnDescriptor = NULL;

NSAppleScript* scriptObject;
scriptObject = [[NSAppleScript alloc] initWithSource:@"try\n
run application \"Macintosh HD:Applications:_Sandbox-AppleScript0.app\"\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
         }
    }
}

      

0


source







All Articles