Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OSX/Swift: Call function when screen becomes available

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:

  • Check for changes in sleep/wake state or
  • Use CGDisplayReconfigurationCallback or
  • Listen for a NSWorkspaceScreensDidWakeNotification

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.

like image 905
yesthisisjoe Avatar asked Jan 04 '16 19:01

yesthisisjoe


2 Answers

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");
}
like image 147
rocky Avatar answered Oct 20 '22 09:10

rocky


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.

like image 2
Amin Negm-Awad Avatar answered Oct 20 '22 10:10

Amin Negm-Awad