由于某种原因,我没有收到屏幕已锁定和屏幕已解锁通知。我定义了屏幕保护程序启动后 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
}
}
使用 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];
}
在斯威夫特中:
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)
现在通知名称的语法略有不同。
DistributedNotificationCenter.default().addObserver(forName: NSNotification.Name(rawValue: "com.apple.screenIsLocked"),
object: nil,
queue: .main) { [weak self] _ in
// Handle it
}
DistributedNotificationCenter.default().addObserver(forName: NSNotification.Name(rawValue: "com.apple.screenIsUnlocked"),
object: nil,
queue: .main) { [weak self] _ in
// Handle it
}