Not getting screenLock notification on Swift 4 on mac

不问归期 提交于 2020-01-06 06:30:19

问题


For some reason I'm not getting the ScreenIsLocked and ScreenIsUnlocked notifications. I defined that the screen get locked 0 seconds after the screen saver starts and yet no log:

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    @objc func screenLocked() {
        NSLog("yes")
    }

    func applicationDidFinishLaunching(_ aNotification: Notification) {
        // Insert code here to initialize your application

        NotificationCenter.default.addObserver(
            self,
            selector: #selector(AppDelegate.screenLocked),
            name: Notification.Name("com.apple.screenIsLocked"),
            object: nil)

        NotificationCenter.default.addObserver(
            self,
            selector: #selector(AppDelegate.screenLocked),
            name: Notification.Name("com.apple.screenIsUnlocked"),
            object: nil)

        NotificationCenter.default.addObserver(
            self,
            selector: #selector(AppDelegate.screenLocked),
            name: Notification.Name("com.apple.screensaver.didstart"),
            object: nil)

        NotificationCenter.default.addObserver(
            self,
            selector: #selector(AppDelegate.screenLocked),
            name: Notification.Name("com.apple.screensaver.didstop"),
            object: nil)


    }

    func applicationWillTerminate(_ aNotification: Notification) {
        // Insert code here to tear down your application

    }


}

回答1:


Use NSDistributedNotificationCenter

This is from a post by Kane Cheshire:

https://kanecheshire.com/blog/2014/10/13/351/

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {

    NSDistributedNotificationCenter *center = [NSDistributedNotificationCenter defaultCenter];
    [center addObserver:self
               selector:@selector(screenLocked)
                   name:@"com.apple.screenIsLocked"
                 object:nil];

    [center addObserver:self
               selector:@selector(screenUnlocked)
                   name:@"com.apple.screenIsUnlocked"
                 object:nil];
}

In Swift:

DistributedNotificationCenter.default().addObserver(self,
                                                    selector: #selector(screenLocked),
                                                    name: "com.apple.screenIsLocked",
                                                    object: nil)

DistributedNotificationCenter.default().addObserver(self,
                                                    selector: #selector(screenLocked),
                                                    name: "com.apple.screenIsUnlocked",
                                                    object: nil)


来源:https://stackoverflow.com/questions/49914330/not-getting-screenlock-notification-on-swift-4-on-mac

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