What event is fired when Mac is back from sleep?

廉价感情. 提交于 2019-11-30 13:58:53

问题


I am developing an app in Xcode on Mac and would like to know the event which is fired when the mac gets back from sleep. AwakeFromNib doesn't seem to work.

Thanks !


回答1:


Just found it:

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



回答2:


For 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)
}

For 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)
}



回答3:


You can use IORegisterForSystemPower().

Connects the caller to the Root Power Domain IOService for the purpose of receiving sleep & wake notifications for the system. Does not provide system shutdown and restart notifications.

io_connect_t IORegisterForSystemPower (
    void *refcon, 
    IONotificationPortRef *thePortRef, 
    IOServiceInterestCallback callback, 
    io_object_t *notifier ) ;  

Take a look at Q:How can my application get notified when the computer is going to sleep or waking from sleep? How to I prevent sleep?



来源:https://stackoverflow.com/questions/9247710/what-event-is-fired-when-mac-is-back-from-sleep

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