You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在macOS上监听systemDidWake系统唤醒事件?

监听Mac深度睡眠唤醒事件补充方案

你的代码目前仅监听了屏幕锁定/解锁的分布式通知,但Mac从深度睡眠(未接电源休眠8-12小时以上)唤醒时,com.apple.screenIsUnlocked通知不会触发,需要补充监听系统级的唤醒事件。可以通过NSWorkspace提供的官方通知来实现,以下是修改后的完整代码:

#!/usr/bin/env swift

import Foundation
import AppKit  // 需导入AppKit以使用NSWorkspace

class SystemEventObserver {
    init() {
        let dnc = DistributedNotificationCenter.default()
        let workspace = NSWorkspace.shared

        // 监听屏幕锁定
        let lockObserver = dnc.addObserver(forName: NSNotification.Name("com.apple.screenIsLocked"), object: nil, queue: .main) { _ in
            NSLog("Screen Locked")
        }

        // 监听屏幕解锁
        let unlockObserver = dnc.addObserver(forName: NSNotification.Name("com.apple.screenIsUnlocked"), object: nil, queue: .main) { _ in
            NSLog("Screen Unlocked")
        }

        // 监听系统唤醒(包括深度睡眠唤醒)
        let wakeObserver = workspace.notificationCenter.addObserver(forName: NSWorkspace.didWakeNotification, object: nil, queue: .main) { _ in
            NSLog("System Did Wake from Sleep")
        }

        RunLoop.main.run()
    }
}

let _ = SystemEventObserver()

关键说明:

  1. 导入AppKit:NSWorkspace属于AppKit框架,必须导入才能使用系统唤醒通知。
  2. 系统唤醒通知:NSWorkspace.didWakeNotification是苹果官方提供的系统唤醒事件通知,无论Mac是从浅睡眠还是深度睡眠唤醒,都会触发该通知。
  3. 事件覆盖:结合原有的屏幕锁定/解锁通知,可完整覆盖日常休眠唤醒、主动锁屏解锁的所有场景。

内容的提问来源于stack exchange,提问作者Pylinux

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 16:00:00