Reputation: 1028
I'm developing a Cocoa app and I need to perform different actions before the app get closed. I need to know when the app is closed due to a restart and when due to a shutdown.
Through NSWorkspaceWillPowerOffNotification
the app recieves a notification regardless of the fact that it's a restart or a shutdown.
Is there a way to identify the cause of poweroff?
Upvotes: 3
Views: 636
Reputation: 51
you probably don't need to use NSWorkspaceWillPowerOffNotification
and you can just use the applicationShouldTerminate:
delegate with the code below. your app is getting terminated anyway if the system is getting restarted/shutdown or the user is logging out.
from Apple Developer Forum : How to determine if an application "quit" is because of a logout or restart/shutdown?
https://developer.apple.com/forums/thread/94126
//#import <Foundation/Foundation.h>
//#import <Carbon/Carbon.h> // for kEventParamReason
- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender
{
NSAppleEventDescriptor* appleEventDesc = [[NSAppleEventManager sharedAppleEventManager] currentAppleEvent];
NSAppleEventDescriptor* whyDesc = [appleEventDesc attributeDescriptorForKeyword:kEventParamReason];
OSType why = [whyDesc typeCodeValue];
switch (why) {
case kAEShutDown: {
NSLog(@"kAEShutDown");
break;
}
case kAERestart: {
NSLog(@"kAERestart");
break;
}
case kAEReallyLogOut: {
NSLog(@"kAEReallyLogOut");
break;
}
}
...
return NSTerminateNow;
}
Upvotes: 0