NSWorkspaceWillPowerOffNotification 从未被调用

Yan*_*ivH 5 macos nsnotifications nsworkspace macos-sierra

我正在尝试在后台进程中运行一个程序,该程序将注册系统中的每个关闭事件。

通过注册 NSWorkspaceWillPowerOffNotification 来实现此目的,如下所示:

#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
Run Code Online (Sandbox Code Playgroud)

由于某种我无法理解的原因, NSWorkspaceWillPowerOffNotification 处理程序永远不会被调用!

还将以下内容添加到我的 .plist 中:

<key>NSSupportsSuddenTermination</key>
<false/>
Run Code Online (Sandbox Code Playgroud)

但关闭系统时仍然没有通知注册。

知道为什么吗?

Yan*_*ivH 4

备查:

我无法注册上述活动并看到它发生。

最后,我采用了不同的方法: 苹果开源电源管理

在这里,您可以看到我们的通知名称,例如:“com.apple.system.loginwindow.logoutNoReturn”

您可以注册这些内容,这样就可以了。

希望有一天这会对某人有所帮助:)