swiftmacoscocoaquartz

Swift: How to observe if screen is locked in macOS


I want to detect if the user has locked his screen (in macOS) using Swift.

Based on this answer I’ve created the following code:

import Cocoa
import Quartz

if let dict = Quartz.CGSessionCopyCurrentDictionary() as? [String : Any] {
    let locked = dict["CGSSessionScreenIsLocked"]
    print(locked as? String ?? "")
}

...which seems to work fine if I explicitly run the code.

But how is it possible to observe the value so I get notified when the value got changed?


Solution

  • You can observe distributed notifications. They are not documented.

    let dnc = DistributedNotificationCenter.default()
    
    let lockObserver = dnc.addObserver(forName: .init("com.apple.screenIsLocked"),
                                   object: nil, queue: .main) { _ in
        NSLog("Screen Locked")
    }
    
    let unlockObserver = dnc.addObserver(forName: .init("com.apple.screenIsUnlocked"),
                                     object: nil, queue: .main) { _ in
        NSLog("Screen Unlocked")
    }