3

我对这个应用程序开发领域比较陌生。我试图在用户登录和注销事件期间收到通知。我已经尝试过NSWorkSpaceNotifications,但它对我不起作用。

有人可以帮我吗。

-(void)logInLogOutNotifications{
    NSNotificationCenter *notCenter;
    notCenter = [[NSWorkspace sharedWorkspace] notificationCenter];
    [notCenter addObserver:self
                  selector:@selector(observerMethod)
                      name:NSWorkspaceWillPowerOffNotification object:nil]; 
}

-(void)observerMethod:(NSNotification *)senderNotification;{

    NSLog(@"System Logout Notification is called***********************");

}
4

4 回答 4

2

NSApplicationMain开始RunLoop. 您正在从 main() 函数调用 logInLogOutNotifications 函数,因此您应该运行 runloop。或调用 logInLogOutNotificationsapplicationDidFinishLaunching

-(void)logInLogOutNotifications{
    NSNotificationCenter *notCenter;
    notCenter = [[NSWorkspace sharedWorkspace] notificationCenter];
    [notCenter addObserver:self
                  selector:@selector(observerMethod)
                      name:NSWorkspaceWillPowerOffNotification object:nil]; 
[[NSRunLoop currentRunLoop] run];
}
于 2013-06-18T12:30:02.107 回答
2

你的方法有一个参数,所以你应该改变

@selector(observerMethod)

@selector(observerMethod:)
于 2013-12-02T21:29:41.593 回答
2

如果您像我一样在弄清楚为什么您没有收到NSWorkspaceWillPowerOffNotification通知时遇到问题,请确保您将自己设置为[[NSWorkspace sharedWorkspace] notificationCenter]-NOT-的观察者[NSNotificationCenter defaultCenter]

我花了一天的大部分时间试图调试为什么我没有收到该通知,因为我没有清楚地阅读答案!

于 2015-08-28T13:07:42.223 回答
0

如果您想知道用户何时辞职或活跃,您只需订阅以下通知:

斯威夫特 3

    NSWorkspace.shared().notificationCenter.addObserver(self, selector: #selector(sessionResignActive(_:)), name: NSNotification.Name.NSWorkspaceSessionDidResignActive, object: nil)
    NSWorkspace.shared().notificationCenter.addObserver(self, selector: #selector(sessionBecomeActive(_:)), name: NSNotification.Name.NSWorkspaceSessionDidBecomeActive, object: nil)
于 2017-03-01T01:49:57.497 回答