What event is fired when Mac is back from sleep?

前端 未结 3 1835
逝去的感伤
逝去的感伤 2020-12-31 09:41

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

相关标签:
3条回答
  • 2020-12-31 10:08

    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];
    }
    
    0 讨论(0)
  • 2020-12-31 10:23

    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?

    0 讨论(0)
  • 2020-12-31 10:24

    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)
    }
    
    0 讨论(0)
提交回复
热议问题