I need to quit other applications in cocoa. I have a userInfo dictionary from a notification that tells me the name of the application. I tried the methods terminate and forceTerminate, but they did not work (I think they are only available in snow leopard.)
We use -[NSWorkspace runningApplications]
. It requires 10.6 or higher.
void SendQuitToProcess(NSString* named)
{
for ( id app in [[NSWorkspace sharedWorkspace] runningApplications] )
{
if ( [named isEqualToString:[[app executableURL] lastPathComponent]])
{
[app terminate];
}
}
}
otherwise, you'll have to use AppleScript. You can do something corny like this:
void AESendQuitToProcess(const char* named)
{
char temp[1024];
sprintf(temp, "osascript -e \"tell application \\\"%s\\\"\" -e \"activate\" -e \"quit\" -e \"end tell\"", named);
system(temp);
}
The best solution (accounting for all the different API's available in the last 3-4 versions of OS X) is going to be using AppleScript. Just generate the necessary script in Obj-C/Python/Java whatever it is you are actually using (I'm assuming Obj-C since you specifically said 'In Cocoa'). And execute it using the NSAppleScript class (a contrived example):
// Grab the appName
NSString *appName = [someDict valueForKey:@"keyForApplicationName"];
// Generate the script
NSString *appleScriptString =
[NSString stringWithFormat:@"tell application \"%@\"\nquit\nend tell",
appName];
// Execute the script
NSDictionary *errorInfo = nil;
NSAppleScript *run = [[NSAppleScript alloc] initWithSource:theScript];
NSAppleEventDescriptor *theDescriptor = [run executeAndReturnError:&errorInfo];
// Get the result if your script happens to return anything (this example
// really doesn't return anything)
NSString *theResult = [theDescriptor stringValue];
NSLog(@"%@",theResult);
This effectively runs a script that (if appName was 'Safari') looks like:
tell application "Safari"
quit
end tell
That or check out this SO question
Terminating Another App Running - Cocoa
You can send the application a quit AppleEvent, requesting the application quit, but I don't think you can force an application to quit without elevated privileges. Take a look at the Scripting Bridge framework for the most Cocoa-y way to send the required events.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With