I want my OSX app to call a function when the user's screen becomes available, ex: their computer wakes from sleep or the user turns on their screen. Basically any time the user goes from having no screen active to having one active, I would like my function to be called.
I'm not sure if the best way to do this is to:
Which of these seems like the best way to do this, or should I do something else entirely? Some kind of example Swift code would be really helpful since snippets of code implementing any of these seem to be few and far between. Thanks.
I was able to receive notifications for screen lock and screen unlock on OS X 10.10.5. Sorry I don't know Swift yet so here's the Objective-C:
NSDistributedNotificationCenter *center = [NSDistributedNotificationCenter defaultCenter];
[center addObserver:self selector:@selector(screenIsLocked) name:@"com.apple.screenIsLocked" object:nil];
[center addObserver:self selector:@selector(screenIsUnlocked) name:@"com.apple.screenIsUnlocked" object:nil];
- (void)screenIsLocked {
NSLog(@"screen is locked");
}
- (void)screenIsUnlocked {
NSLog(@"screen is unlocked");
}
Well, first of all you have to test, whether you can get the solution for all situations with the different technologies. There are many situations that turns on the display (system restart, awake from sleep, connecting/disconneting screens, …) and I'm not sure, whether they are all triggered by all technologies.
However, as a general rule: You want to know, when the screen is activated. So use the notification that tells you that the screen is activated. This is NSWorkspaceScreensDidWakeNotification
. As long it works I would always use the technique that is closest to what I want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With