Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you detect key up / key down events from a hardware keyboard on iOS?

While there are many methods posted on SO regarding hacking keyboards to work, for example, How can I support the up and down arrow keys with a Bluetooth keyboard under iOS 7, or Receive iPhone keyboard events, none of them are documented.

Is it possible to detect a keyUp: / keyDown: input event from a hardware keyboard (e.g. bluetooth) in iOS using public APIs?

like image 216
mseddon Avatar asked Feb 27 '14 23:02

mseddon


1 Answers

As of iOS 13.4, this is now possible due to the introduction of UIKey, which is included on pressesBegan events now when a keyboard key is pressed. this guide from Swift By Sundell covers some examples. Here is the relevant bit:

class EditorViewController: UIViewController {
    ...

    override func pressesBegan(_ presses: Set<UIPress>,
                               with event: UIPressesEvent?) {
        super.pressesBegan(presses, with: event)
        presses.first?.key.map(keyPressed)
    }

    override func pressesEnded(_ presses: Set<UIPress>,
                               with event: UIPressesEvent?) {
        super.pressesEnded(presses, with: event)
        presses.first?.key.map(keyReleased)
    }

    override func pressesCancelled(_ presses: Set<UIPress>,
                                   with event: UIPressesEvent?) {
        super.pressesCancelled(presses, with: event)
        presses.first?.key.map(keyReleased)
    }
}
like image 102
Benjamin Kindle Avatar answered Oct 13 '22 03:10

Benjamin Kindle