OSX/Swift: Call function when screen becomes available

孤者浪人 提交于 2019-12-21 04:09:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!