NSWorkspaceWillPowerOffNotification never called

I am trying to run a program in a background process that will log every shutdown event in the system.

After doing this, register with NSWorkspaceWillPowerOffNotification, as shown below:

#import <AppKit/AppKit.h>

@interface ShutDownHandler : NSObject <NSApplicationDelegate>

- (void)computerWillShutDownNotification:(NSNotification *)notification;

@end


int main(int argc, char* argv[]) {
    NSNotificationCenter *notCenter;

    notCenter = [[NSWorkspace sharedWorkspace] notificationCenter];

    ShutDownHandler* sdh = [ShutDownHandler new];

    [NSApplication sharedApplication].delegate = sdh;

    [notCenter addObserver:sdh
                  selector:@selector(computerWillShutDownNotification:)
                      name:NSWorkspaceWillPowerOffNotification
                    object:nil];

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        [[NSFileManager defaultManager] createFileAtPath:@"./output.txt" contents:nil attributes:nil];
    });

    [[NSRunLoop currentRunLoop] run];

    return 0;
}


@implementation ShutDownHandler

- (void)computerWillShutDownNotification:(NSNotification *)notification {
    NSFileHandle* file = [NSFileHandle fileHandleForUpdatingAtPath: @"./output.txt"];
    [file seekToEndOfFile];

    NSDateFormatter* fmt = [NSDateFormatter new];
    [fmt setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate* current = [NSDate date];

    NSString* dateStr = [fmt stringFromDate:current];
    [dateStr writeToFile:@"./output.txt" atomically:YES encoding:NSUTF8StringEncoding error:nil];
}

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

@end

For some reason I can't figure out the NSWorkspaceWillPowerOffNotification handler is never called!

Also added the following to my .plist:

<key>NSSupportsSuddenTermination</key>
<false/>

but when my system shuts down, registration is not registered.

Any idea on why ??

+3
source share
2 answers

For future reference:

I could not register in the above event and see his fire.

, : Apple

, , : "Com.apple.system.loginwindow.logoutNoReturn"

, .

, -:)

+1

, , , daemon, plist /Library/LaunchDeamon? . Cocoa application

, LaunchDaemon, AppKit.

deamon.

+1

All Articles