Pylinux
Pylinux

Reputation: 11836

How to listen for systemDidWake events on macOS?

How do I listen for an event for when the Mac wakes up from sleep?

I have code to listen for screen lock and unlock events, BUT when the system wakes from deep sleep1 the unlock event doesn't fire. Therefore I want to also listen for the systemDidWake or similar event.

The code I have now for listening for lock/unlock events look like this:

#!/usr/bin/env swift

import Foundation

class ScreenLockObserver {
    init() {
        let dnc = DistributedNotificationCenter.default()

        // listen for screen lock
        let _ = dnc.addObserver(forName: NSNotification.Name("com.apple.screenIsLocked"), object: nil, queue: .main) { _ in
            NSLog("Screen Locked")
        }

        // listen for screen unlock
        let _ = dnc.addObserver(forName: NSNotification.Name("com.apple.screenIsUnlocked"), object: nil, queue: .main) { _ in
            NSLog("Screen Unlocked")
        }

        RunLoop.main.run()
    }
}

let _ = ScreenLockObserver()

I'm testing this on a M3 MacBook running macOS Sonoma 14.1.


1 When the Mac has been closed for 8-12+ hours, preferably without power.

Upvotes: 0

Views: 149

Answers (0)

Related Questions