Search code examples
iosswiftkeyboardremote-control

Handling external keyboard presses without showing keyboard on screen on iOS app


I have a private iOS app that I want to control using an external keyboard connected via Bluetooth. I don't want any UITextField or UITextView in my app, or at least I don't want the keyboard to show all the time. Is there a way for me listen to these keyboard events from the physical keyboard? thanks.


Solution

  • UIKeyCommands

    To listen keys from keyboard, you can override the keyCommands variable on your ViewController (It's an array so you can put many shortcuts):

    override var keyCommands: [UIKeyCommand]? {
        return [
            UIKeyCommand(input: "Q",
                         modifierFlags: [],
                         action: #selector(self.close),
                         discoverabilityTitle: "Close app")
        ]
    }
    
    func close() {
        exit(0)
    }
    

    Input is the key to use, for example CMD+Q (only put Q). Action is the selector to call and discoverabilityTitle is the title of the shortcut, for example "Close app". It will be displayed in iPad when the user holds the CMD key.

    It only works with CMD keys and other specials keys:

    UIKeyInputUpArrow
    UIKeyInputDownArrow
    UIKeyInputLeftArrow
    UIKeyInputRightArrow
    UIKeyInputEscape