问题
For some reason I'm not getting the ScreenIsLocked and ScreenIsUnlocked notifications. I defined that the screen get locked 0 seconds after the screen saver starts and yet no log:
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:
Use NSDistributedNotificationCenter
This is from a post by 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];
}
In 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)
来源:https://stackoverflow.com/questions/49914330/not-getting-screenlock-notification-on-swift-4-on-mac