How to migrate NSWorkspace notifications to Swift 4?

佐手、 提交于 2019-12-22 15:25:53

问题


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.



来源:https://stackoverflow.com/questions/44402016/how-to-migrate-nsworkspace-notifications-to-swift-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!