How to migrate NSWorkspace notifications to Swift

2019-05-23 00:12发布

问题:

In Swift 3 I registered for sleep and wake notifications with this code:

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)

but after migrating to Swift 4, I get this error after applying the suggested fixes:

Type 'NSNotification.Name' has no member 'NSWorkspace'

How do I do this in Swift 4?

回答1:

To fix this, you just need to adjust the code referencing the notification's name from NSNotification.Name.NSWorkspaceWillSleep to NSWorkspace.willSleepNotification. The Swift 4 version is:

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)

You can see Apple's API diffs for this change here.