How to catch button press event from external keyboard in swift while full keyboard access is active?

101 Views Asked by At

I have following code in ViewController of a swift iOS application:

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    override func pressesBegan(_ presses: Set<UIPress>, with event: UIPressesEvent?) {
        let keyCode = presses.first?.key?.keyCode.rawValue
        print("Pressed key with keycode:" )
        print(keyCode)
    }
}

The method pressesBegan from UIResponder-Class is overwritten. After launching the application on an iOS device connected with a keyboard, it is possible to type buttons on the connected keyboard and the HID values of the keys are printed out in the console and all works fine.

When I enable the "Full keyboard access" in Settings > Accessibility > Keyboards of the iOS device, the recognition of some keys like spacebar and tab are not working any more. It seems like the "Full keyboard access" of iOS device handles the button presses and so it does not reach the pressesBegan method.

I've also tried to handle these keys as UIKeyCommands. Following example shows how I used it for spacebar:

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    override var keyCommands: [UIKeyCommand]? {
            let commands = [
                UIKeyCommand(input: " ", modifierFlags: [], action: #selector(spacebarAction)),
            ]
            // if your target is iOS 15+ only, you can remove `if` and always apply this rule
            if #available(iOS 15, *) {
                commands.forEach { $0.wantsPriorityOverSystemBehavior = true }
            }
            return commands
    }
    
    @objc func spacebarAction() { print("command works.") }
}

The same behavior. When "Full keyboard access" is disabled, the press of spacebar is recognized and code inside spacebarAction is execute. No reaction when it's enabled.

What can I do to make it work with enabled "Full keyboard access"?

0

There are 0 best solutions below