【发布时间】:2012-03-04 02:22:09
【问题描述】:
我正在 Mac 上的 Xcode 中开发一个应用程序,想知道当 mac 从睡眠中恢复时触发的事件。 AwakeFromNib 似乎不起作用。
【问题讨论】:
标签: xcode macos cocoa events sleep
我正在 Mac 上的 Xcode 中开发一个应用程序,想知道当 mac 从睡眠中恢复时触发的事件。 AwakeFromNib 似乎不起作用。
【问题讨论】:
标签: xcode macos cocoa events sleep
对于 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)
}
【讨论】:
刚刚找到:
- (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];
}
【讨论】:
您可以使用IORegisterForSystemPower()。
将调用者连接到 Root Power Domain IOService 以达到目的 接收系统的睡眠和唤醒通知。才不是 提供系统关闭和重启通知。
io_connect_t IORegisterForSystemPower (
void *refcon,
IONotificationPortRef *thePortRef,
IOServiceInterestCallback callback,
io_object_t *notifier ) ;
【讨论】: