Listening for hardware keyboard key presses in Swift

2.6k views Asked by At

I'd like to add hardware keyboard support to my app so users may trigger a function to be called by pressing a certain key on the keyboard at any time. I found this article and was able to make it work great in Objective-C. I've converted it to Swift, but for some reason the keyPressed method is not being called after I press "c". I confirmed keyCommands is called as soon as the user presses any key on the keyboard. I'm testing with the iOS Simulator and the Mac's keyboard.

What is the problem here in my Swift code?

override func canBecomeFirstResponder() -> Bool {
    return true
}

func keyCommands() -> [AnyObject]? {
    var keyCommands = []

    struct Static {
        static var onceToken : dispatch_once_t = 0
    }
    dispatch_once(&Static.onceToken) {
        let command = UIKeyCommand(input: "c", modifierFlags: nil, action: "keyPressed:")
        keyCommands = [command]
    }

    return keyCommands
}

func keyPressed(command: UIKeyCommand) {
    println("user pressed c") //never gets called
}
1

There are 1 answers

0
Jordan H On BEST ANSWER

The problem is keyCommands is called every time a key is pressed and every time I initialize an array so that it is empty, then I return it. So the first time the method is called it will return the correct array, but the second time it will return an array with no content.

To fix the issue, I decided to store the key commands array as a property, then in the method I check if it is nil, and if so then I create it, otherwise I just return the stored property.