Question

I am fresher for this application development field. I am tried to get notifications during user login & logout events. I have tried with NSWorkSpaceNotifications, but it does not working for me.

Can somebody help me please.

-(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***********************");

}
Was it helpful?

Solution

NSApplicationMain Begin the RunLoop. You are calling logInLogOutNotifications function from main() function, so you shoud run runloop. or call logInLogOutNotifications in applicationDidFinishLaunching

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

OTHER TIPS

Your method takes one argument, so you should change

@selector(observerMethod)

to

@selector(observerMethod:)

If you're like me and having problems figuring out why in the world you are not getting receiving the NSWorkspaceWillPowerOffNotification notification, make sure you are setting yourself as an observer of [[NSWorkspace sharedWorkspace] notificationCenter] and -NOT- [NSNotificationCenter defaultCenter]!

I spent the better part of a day trying to debug why I wasn't getting that notification because I didn't read the answer clearly!

If you want to know when user resign or become active you just should subscribe to the following notifications:

Swift 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)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top