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

Swift开发的macOS Ventura+应用如何检查Input Monitoring权限状态

在macOS Ventura及以上版本中检查Input Monitoring权限的方法

在macOS Ventura(13.0)及以后版本中,Input Monitoring已从Accessibility权限中独立出来,因此原有的AXIsProcessTrusted()等接口无法直接判断该权限的状态。以下是两种可靠的判定方法:

方法一:使用Accessibility框架的专用检查接口

通过AXIsProcessTrustedWithOptions并传入指定Input Monitoring的参数,可以直接查询权限状态:

import ApplicationServices

func hasInputMonitoringPermission() -> Bool {
    let checkOptions: [NSString: Any] = [
        kAXTrustedCheckOptionInputMonitoring: true
    ]
    return AXIsProcessTrustedWithOptions(checkOptions as CFDictionary)
}

该方法返回true表示应用已获得Input Monitoring权限,返回false则表示未授权或权限被用户拒绝。

方法二:通过实际操作验证权限

尝试执行需要Input Monitoring权限的操作(比如创建事件监听tap),通过操作是否成功来判断权限状态:

import Cocoa

func isInputMonitoringPermissionGranted() -> Bool {
    do {
        // 尝试创建监听键盘按下事件的tap
        let eventTap = try CGEvent.tapCreate(
            tap: .cgSessionEventTap,
            place: .headInsertEventTap,
            options: .defaultTap,
            eventsOfInterest: CGEventMask(1 << CGEventType.keyDown.rawValue),
            callback: { _, _, _ in nil },
            userInfo: nil
        )
        
        guard let tap = eventTap else { return false }
        // 清理资源
        CFRelease(tap)
        return true
    } catch {
        // 创建失败说明权限未授予
        return false
    }
}

如果创建事件tap成功,说明权限已授予;若抛出错误或创建失败,则表示权限未开启。

注意事项

  • 无论使用哪种方法,都必须在应用的Info.plist中添加NSInputMonitoringUsageDescription键,并填写清晰的权限使用说明,否则系统会拒绝权限请求。
  • 方法一更高效直接,推荐作为首选检查方式;方法二则适合需要同时验证权限可用性的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 06:04:56