Search code examples
iosiphoneipadkeyboard

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?


Solution

  • 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)
        }
    }