How to distinguish between various reasons for application termination in Cocoa?

I would like my application to ask for confirmation before logging out, unless it shuts down during a shutdown or restart (because when OS X tries to apply security updates at midnight, it gets stuck in the β€œAre you sure?” Window. messages).

How can I find out what triggered the completion? In [NSApp terminate:sender] sender is always nil .

My first thought was to ask only if the "Exit" main menu item is activated, but the user can also terminate the application from the Dock menu or by pressing Cmd + Q while holding Cmd + Tab, and I would like to ask for confirmation in these cases too .

+6
source share
1 answer

You may receive a notification when the system is about to turn off the power, restart, or log off. This is not a regular notification, but a notification of the workspace.

You can register for notification as follows:

 - (void)applicationDidFinishLaunching:(NSNotification *)aNotification { //...more code... self.powerOffRequestDate = [NSDate distantPast]; NSNotificationCenter *wsnCenter = [[NSWorkspace sharedWorkspace] notificationCenter]; [wsnCenter addObserver:self selector:@selector(workspaceWillPowerOff:) name:NSWorkspaceWillPowerOffNotification object:nil]; } 

in the notification handler, you should just save the date:

 - (void)workspaceWillPowerOff:(NSNotification *)notification { self.powerOffRequestDate = [NSDate new]; } 

Add

 @property (atomic,strong,readwrite) NSDate *powerOffRequestDate; 

to the appropriate place.

when your application is asked to shut down, you should get this date and check if the computer is going to shut down.

 if([self.powerOffRequestDate timeIntervalSinceNow] > -60*5) { // shutdown immediately } else { // ask user } 

I chose an interval of 5 minutes for the following case: the computer should shut down, but another application cancels this. Your application is still running. After 10 minutes, the user closes your application. In this case, the application should ask the user. It's a little hack, but it's not a β€œcrazy hack," I think ...

Hope this helps.

+2
source

All Articles