Swift: 如何在 macOS 中观察屏幕是否被锁定

Swift: How to observe if screen is locked in macOS

我想检测用户是否使用 Swift 锁定了他的屏幕(在 macOS 中)。

基于 on this answer 我创建了以下代码:

import Cocoa
import Quartz

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

...如果我明确 运行 代码,这似乎工作正常。

但是如何观察值以便在值更改时收到通知?

您可以观察分布式通知。它们没有记录。

let dnc = DistributedNotificationCenter.default()

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

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

使用 Combine(适用于 macOS 10.15+):

import Combine

var bag = Set<AnyCancellable>()

let dnc = DistributedNotificationCenter.default()

dnc.publisher(for: Notification.Name(rawValue: "com.apple.screenIsLocked"))
    .sink { _ in print("Screen Locked" }
    .store(in: &bag)

dnc.publisher(for: Notification.Name(rawValue: "com.apple.screenIsUnlocked"))
    .sink { _ in print("Screen Unlocked" }
    .store(in: &bag)