Mac 从睡眠中恢复时会触发啥事件?
Posted
技术标签:
【中文标题】Mac 从睡眠中恢复时会触发啥事件?【英文标题】:What event is fired when Mac is back from sleep?Mac 从睡眠中恢复时会触发什么事件? 【发布时间】:2012-03-04 02:22:09 【问题描述】:我正在 Mac 上的 Xcode 中开发一个应用程序,想知道当 mac 从睡眠中恢复时触发的事件。 AwakeFromNib 似乎不起作用。
【问题讨论】:
【参考方案1】:对于 Swift 3:
func onWakeNote(note: NSNotification)
print("Received wake note: \(note.name)")
func onSleepNote(note: NSNotification)
print("Received sleep note: \(note.name)")
func fileNotifications()
NSWorkspace.shared().notificationCenter.addObserver(
self, selector: #selector(onWakeNote(note:)),
name: Notification.Name.NSWorkspaceDidWake, object: nil)
NSWorkspace.shared().notificationCenter.addObserver(
self, selector: #selector(onSleepNote(note:)),
name: Notification.Name.NSWorkspaceWillSleep, object: nil)
对于 Swift 4:
@objc func onWakeNote(note: NSNotification)
...
@objc func onSleepNote(note: NSNotification)
...
func fileNotifications()
NSWorkspace.shared.notificationCenter.addObserver(
self, selector: #selector(onWakeNote(note:)),
name: NSWorkspace.didWakeNotification, object: nil)
NSWorkspace.shared.notificationCenter.addObserver(
self, selector: #selector(onSleepNote(note:)),
name: NSWorkspace.willSleepNotification, object: nil)
【讨论】:
【参考方案2】:刚刚找到:
- (void) receiveWakeNote: (NSNotification*) note
NSLog(@"receiveSleepNote: %@", [note name]);
- (void) fileNotifications
//These notifications are filed on NSWorkspace's notification center, not the default
// notification center. You will not receive sleep/wake notifications if you file
//with the default notification center.
[[[NSWorkspace sharedWorkspace] notificationCenter] addObserver: self
selector: @selector(receiveWakeNote:)
name: NSWorkspaceDidWakeNotification object: NULL];
【讨论】:
两件事:您希望对象为“nil”而不是“NULL”,并且您应该格式化您的答案以将您的代码显示为格式化的代码 - 现在它非常不可读。但是很好地回答了你自己的问题! 如何正确格式化代码?我不知道所需的标签...谢谢! 看起来 Parag 打败了你。但在未来,看看编辑器中的按钮。其中一个是一对大括号(“”)。使用它来将选定的文本块格式化为代码。【参考方案3】:您可以使用IORegisterForSystemPower()。
将调用者连接到 Root Power Domain ioservice 以达到目的 接收系统的睡眠和唤醒通知。才不是 提供系统关闭和重启通知。
io_connect_t IORegisterForSystemPower (
void *refcon,
IONotificationPortRef *thePortRef,
IOServiceInterestCallback callback,
io_object_t *notifier ) ;
看看Q:How can my application get notified when the computer is going to sleep or waking from sleep? How to I prevent sleep?
【讨论】:
以上是关于Mac 从睡眠中恢复时会触发啥事件?的主要内容,如果未能解决你的问题,请参考以下文章
当事件触发并尝试在不再存在的对象中执行事件处理程序时会发生啥?