我想检测用户是否使用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 ?? "")
}
...如果我明确运行代码,这似乎可以正常工作。
但是如何观察该值,以便在更改值时得到通知?
答案 0 :(得分:1)
您可以观察分布式通知。它们没有记录。
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")
}
答案 1 :(得分:1)
使用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)