如何将 NSWorkspace 通知迁移到 Swift 4?

How to migrate NSWorkspace notifications to Swift 4?

在 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