问题
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.
回答1:
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");
}
回答2:
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.
来源:https://stackoverflow.com/questions/34598611/osx-swift-call-function-when-screen-becomes-available