我正在尝试在后台进程中运行一个程序,该程序将注册系统中的每个关闭事件。
通过注册到 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
出于某种我无法理解的原因,从未调用 NSWorkspaceWillPowerOffNotification 处理程序!
还将以下内容添加到我的 .plist 中:
<key>NSSupportsSuddenTermination</key>
<false/>
但是在关闭我的系统时仍然没有注册通知。
知道为什么吗?
最佳答案
备查:
我无法注册上述事件并看到它发生。
最后,我采用了不同的方法:
apple open-source power management
在这里,您可以看到我们有通知名称,例如:
“com.apple.system.loginwindow.logoutNoReturn”
你可以注册到那些,这将做到这一点。
希望有一天这会对某人有所帮助:)
关于macos - NSWorkspaceWillPowerOffNotification 从未调用过,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46085718/