从未调用过NSWorkspaceWillPowerOffNoti

从未调用过NSWorkspaceWillPowerOffNoti

本文介绍了从未调用过NSWorkspaceWillPowerOffNotification的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

通过注册NSWorkspaceWillPowerOffNotification来做到这一点,如下所示:

Doing so by registering to NSWorkspaceWillPowerOffNotification as show 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

由于某种我无法理解的原因,从未调用NSWorkspaceWillPowerOffNotification处理程序!

For some reason that I cannot understand, the NSWorkspaceWillPowerOffNotification handler is never called!

还向我的.plist中添加了以下内容:

Also added the following to my .plist:

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

但关闭系统时仍未注册任何通知.

but still no notification is register when shutting down my system.

关于为什么的任何想法?

Any idea as to why??

推荐答案

供以后参考:

我无法注册上述事件并看到它触发.

I was not able to register to the above event and see it fire.

最后,我采用了另一种方法:苹果开源电源管理

Finally, I went with a different approach:apple open-source power management

在这里,您可以看到我们有一些通知名称,例如:"com.apple.system.loginwindow.logoutNoReturn"

Here, you can see we have notifications names such as:"com.apple.system.loginwindow.logoutNoReturn"

您可以向那些注册,这将解决问题.

You can register to those, and that will do the trick.

希望有一天有帮助的人:)

Hope this will help someone one day :)

这篇关于从未调用过NSWorkspaceWillPowerOffNotification的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 09:52