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

如何在Swift开发的macOS应用中实时监听通知权限的变更?

结论

macOS 目前没有公开的系统通知会在通知权限变更时主动触发,你想要的NSApplication.didChangeSettingsNotification这类公开通知目前不存在。可以通过以下两种方案实现需求:


方案一:优化现有激活监听方案(合规,推荐上架使用)

给原有逻辑加状态缓存判断,过滤无意义的更新调用,完全规避频繁触发的问题:

  1. 本地缓存上一次查询到的通知授权状态
  2. 应用激活时查询最新状态,只有和缓存状态不一致时才执行UI更新逻辑
  3. 状态变更后更新缓存值

示例代码:

// 本地缓存上一次的通知授权状态
private var lastNotificationAuthStatus: UNAuthorizationStatus = .notDetermined

// 页面初始化时先获取初始状态
override func viewDidLoad() {
    super.viewDidLoad()
    UNUserNotificationCenter.current().getNotificationSettings { [weak self] settings in
        self?.lastNotificationAuthStatus = settings.authorizationStatus
    }
    // 监听应用激活通知
    NotificationCenter.default.addObserver(self, selector: #selector(checkNotificationStatus), name: NSApplication.didBecomeActiveNotification, object: nil)
}

@objc private func checkNotificationStatus() {
    UNUserNotificationCenter.current().getNotificationSettings { [weak self] settings in
        DispatchQueue.main.async {
            guard let self = self, 
                  settings.authorizationStatus != self.lastNotificationAuthStatus else {
                // 状态未变化,直接返回不执行更新
                return
            }
            // 状态已变更,更新缓存和UI
            self.lastNotificationAuthStatus = settings.authorizationStatus
            self.updateNotificationStatusUI() // 替换为你自己的UI更新逻辑
        }
    }
}

方案二:实时监听权限变更(仅适用不上架App Store的场景)

如果你的应用不需要上架App Store,可以通过分布式通知中心监听系统私有通知,权限变更时会实时触发:

DistributedNotificationCenter.default().addObserver(
    self,
    selector: #selector(checkNotificationStatus),
    name: NSNotification.Name("com.apple.preference.notifications.changed"),
    object: nil
)

注意:该通知属于私有API,通知名可能随系统版本变更,上架App Store存在被审核拒绝的风险,非特殊场景不推荐使用。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 08:24:06