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.
Check your system's sleep settings To set the amount of time that should pass before your computer goes to sleep, drag the “Turn display off after” slider. You can also deselect “Prevent computer from sleeping automatically when the display is off” in the Power Adapter pane.
Power Nap, available on Mac computers with flash memory, lets some Mac computers stay up to date even while they're sleeping. When your Mac goes to sleep, Power Nap activates periodically to update information.
If the computer still fails to awaken, press the "Power" button but don't hold it down. If none of these three solutions wakes the MacBook, press and hold the "Power" button to perform a hard shut down. Wait a few seconds and then press the "Power" button again to turn the computer on.
If it's a MBP, with the lid open touch (not press) to authenticate Touch ID. If it doesn't wake then it's deep sleep.
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)
}
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With