首页 > 解决方案 > 如何为开发中的 swift 应用程序提供可访问性权限

问题描述

我正在尝试侦听全局键盘事件,并在检测到某些按键时让我的应用程序执行特定操作。为此,我想使用:

class ViewController: NSViewController {

    override func viewDidLoad() {

        super.viewDidLoad()
        //Add keyboard event listener.
        NSEvent.addGlobalMonitorForEvents(matching: .keyDown, handler:
        {
            print("key down!");
            print($0.keyCode);
        });
    }
}

我正在以这种方式检查我的 appDelegate.swift 中的可访问性权限:

func applicationDidFinishLaunching(_ aNotification: Notification) {
    // Insert code here to initialize your application
    //check if the process is trusted for accessibility. This is important for us to listen for keyboard events system wide.
    let checkOptPrompt = kAXTrustedCheckOptionPrompt.takeUnretainedValue() as NSString

    let options = [checkOptPrompt: true]
    let isAppTrusted = AXIsProcessTrustedWithOptions(options as CFDictionary?);
    if(isAppTrusted != true)
    {
        print(  "please allow accessibility API access to this app.");
    }
}

我继续在系统偏好设置中授予 Xcode 可访问权限。但是,我看到日志语句要求授予此应用程序的可访问性权限。简单来说,这是我的大问题,分为两个小问题:

  1. 如何授予此应用完全权限(授予辅助功能权限)?
  2. 如果未启用访问权限,如何显示要求用户授予访问权限的弹出窗口?

标签: swiftmacospermissionsaccessibility

解决方案


推荐阅读