如何使用AppleScript读取macOS请勿打扰(DND)状态?解决返回值始终为1的问题
解决macOS Monterey中读取DND状态总是返回1的问题
我完全懂你遇到的困扰——在macOS Monterey里用defaults -currentHost read ~/Library/Preferences/ByHost/com.apple.notificationcenterui doNotDisturb这个命令,不管请勿打扰实际是开还是关,返回值永远是1,根本没法判断真实状态。这其实是因为Monterey系统里DND状态的存储机制变了,旧的plist键已经不再实时更新了。
为什么旧方法失效?
在macOS Monterey及后续版本中,com.apple.notificationcenterui.plist文件里的doNotDisturb字段不再反映当前的DND实时状态,它可能只是存储了某个初始设置或者历史配置,所以不管你实际开关DND,这个值都不会变化,自然一直返回1。
正确的解决方案
推荐用AppleScript直接调用系统事件来获取实时状态,这是最可靠的方式:
tell application "System Events" set dndIsEnabled to do not disturb enabled of notification center end tell return dndIsEnabled
这个脚本会直接返回true(DND开启)或false(DND关闭),完全准确。
如果需要在shell环境中调用,也可以用osascript包装这个逻辑:
osascript -e 'tell application "System Events" to return do not disturb enabled of notification center'
在AppleScript里调用的话,就写成:
set dndStatus to do shell script "osascript -e 'tell application \"System Events\" to return do not disturb enabled of notification center'" -- 这里dndStatus会是字符串"true"或"false",可以转成布尔值 set dndIsEnabled to dndStatus as boolean return dndIsEnabled
测试一下上面的方法,就能准确获取当前的DND状态了。
内容的提问来源于stack exchange,提问作者user4150758
相关产品推荐
相关产品推荐

