yskywalker
yskywalker

Reputation: 95

Detect pending system shutdown with cocoa

How do I detect when a computer is about to shut down with cocoa? There doesn't seem to be anything out there on the internet. This has to differentiate between shutdown and logout.

Can anybody help me with this?

Upvotes: 2

Views: 1932

Answers (2)

Jiulong Zhao
Jiulong Zhao

Reputation: 1363

Same code as Matthias provided, but change the name of the notification into:

NSWorkspaceWillPowerOffNotification

And if you want to prevent system's shutdown, please add

- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender
{
    return NSTerminateCancel;
}

be sure of using "NSApplicationDelegate"

Good Luck!

Upvotes: 5

Matthias
Matthias

Reputation: 8180

The following code from the official documentation may help you:

 - (void) receiveSleepNote: (NSNotification*) note
 {
     NSLog(@"receiveSleepNote: %@", [note name]);
 }

 - (void) receiveWakeNote: (NSNotification*) note
 {
     NSLog(@"receiveSleepNote: %@", [note name]);
 }

 - (void) fileNotifications
 {
     //These notifications are filed on NSWorkspace's notification center, not the default 
     // notification center. You will not receive sleep/wake notifications if you file 
     //with the default notification center.
     [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver: self 
        selector: @selector(receiveSleepNote:) 
        name: NSWorkspaceWillSleepNotification object: NULL];

     [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver: self 
        selector: @selector(receiveWakeNote:) 
        name: NSWorkspaceDidWakeNotification object: NULL];
 }

For more information see: https://developer.apple.com/library/mac/#qa/qa1340/_index.html

Upvotes: 1

Related Questions