Listening to hardware keyboard keys in Swift

I would like to add hardware keyboard support to my application so that users can invoke a function called by pressing a specific key on the keyboard at any time. I found this article and was able to make it work great in Objective-C. I converted it to Swift, but for some reason the method is keyPressed

not called after pressing "c". I have confirmed that it keyCommands

is called as soon as the user presses any key on the keyboard. I am testing iOS simulator and Mac keyboard.

What is the problem 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
}

      

+3


source to share


1 answer


The problem keyCommands

is thrown every time a key is pressed, and every time I initialize the array so that it is empty, 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 problem, I decided to save the command array as a property and then in the method that I check, if it is nil

, and if so, then I create it, otherwise I will just return the stored property.

+2


source







All Articles