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

如何根据macOS专注设置(勿扰模式)定义应用程序行为?

检测macOS勿扰模式状态的可行方案
  • 用INFocusStatusCenter正确检测勿扰状态
    勿扰模式是系统预设的专注状态,你之前的代码没精准匹配它的标识符。正确的做法是检查activeFocusIdentifiers里是否包含com.apple.DoNotDisturb:

    import Intents
    
    // 单次检测勿扰状态
    func checkDoNotDisturb() async {
        do {
            let focusStatus = try await INFocusStatusCenter.default.focusStatus
            let isDNDActive = focusStatus.activeFocusIdentifiers.contains("com.apple.DoNotDisturb")
            // 这里写你的逻辑:勿扰开就不自动开窗口,否则开类通知窗口
            if isDNDActive {
                // 勿扰启用逻辑
            } else {
                // 勿扰未启用逻辑
            }
        } catch {
            print("获取专注状态失败:\(error)")
        }
    }
    
    // 实时监听状态变化
    func listenForDNDChanges() {
        INFocusStatusCenter.default.addObserver(self) { [weak self] status in
            let isDNDActive = status.activeFocusIdentifiers.contains("com.apple.DoNotDisturb")
            self?.adjustAppBehavior(isDNDActive: isDNDActive)
        }
    }
    
    func adjustAppBehavior(isDNDActive: Bool) {
        // 实现你的窗口控制逻辑
    }
    

    注意:要在Info.plist里加NSFocusStatusUsageDescription,说明应用需要访问专注状态的原因,不然会出现权限报错。

  • AppleScript备选方案
    要是Intents API不好使,可以用AppleScript读取控制中心的勿扰状态,在Swift里调用:

    import Foundation
    
    func isDNDEnabled() -> Bool {
        let script = """
        tell application "System Events"
            tell process "ControlCenter"
                set dndBtn to menu bar item "Focus" of menu bar 1
                return value of attribute "AXDescription" of dndBtn contains "On"
            end tell
        end tell
        """
        let appleScript = NSAppleScript(source: script)
        guard let result = appleScript?.executeAndReturnError(nil), let isOn = result.booleanValue else {
            return false
        }
        return isOn
    }
    

    这种方法需要用户在系统设置的「隐私与安全性」里给应用授权控制中心权限。

  • 关于Notifications API的说明
    你不用通过Notifications API来检测勿扰状态,专注状态API完全够用。Notifications API主要是发通知用的,系统会自动遵循勿扰拦截,但你要自定义窗口行为,直接检测专注状态更直接。focusFilterIntent是给用户自定义过滤规则用的,不是用来获取系统状态的。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 07:22:35