在Swift 3中,我用以下代码注册了睡眠和唤醒通知:

let notificationCenter = NSWorkspace.shared.notificationCenter
notificationCenter.addObserver(self, selector: #selector(AppDelegate.sleepListener), name: NSNotification.Name.NSWorkspaceWillSleep, object: nil)
notificationCenter.addObserver(self, selector: #selector(AppDelegate.wakeUpListener), name: NSNotification.Name.NSWorkspaceDidWake, object: nil)

但是在迁移到swift 4之后,我在应用建议的修复程序后得到了这个错误:
Type 'NSNotification.Name' has no member 'NSWorkspace'

我如何在Swift 4中执行此操作?

最佳答案

要解决此问题,只需将引用通知名称的代码从NSNotification.Name.NSWorkspaceWillSleep调整为NSWorkspace.willSleepNotification。Swift 4版本为:

let notificationCenter = NSWorkspace.shared.notificationCenter
notificationCenter.addObserver(self, selector: #selector(AppDelegate.sleepListener), name: NSWorkspace.willSleepNotification, object: nil)
notificationCenter.addObserver(self, selector: #selector(AppDelegate.wakeUpListener), name: NSWorkspace.didWakeNotification, object: nil)

您可以看到此更改的Apple API差异here

09-18 02:51