当Mac从睡眠状态恢复时会发生什么事?

时间:2012-02-12 09:22:15

标签: xcode macos cocoa events sleep

我正在Mac上的Xcode中开发一个应用程序,并且想知道当mac从睡眠状态恢复时触发的事件。 AwakeFromNib似乎不起作用。

谢谢!

3 个答案:

答案 0 :(得分:10)

刚刚找到它:

- (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];
}

答案 1 :(得分:8)

对于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 :(得分:2)

您可以使用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?