没有在Mac上的Swift 4上获得screenLock通知

时间:2018-04-19 06:40:47

标签: swift macos nsnotificationcenter notificationcenter

出于某种原因,我没有收到ScreenIsLocked和ScreenIsUnlocked通知。我定义屏幕保护程序启动后0秒锁定屏幕,但没有记录:

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 个答案:

答案 0 :(得分:0)

使用NSDistributedNotificationCenter

这是来自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];
}

在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)