iosswiftkeyboardgamecontrolleruikeycommand

iOS Swift Interrupt Keyboard Events


I have problem to intercept keyboard events. I have connected my iOS with SteelSeries Free (gamepad controller) which when connected to iOS will be detected as a Bluetooth Keyboard. This is tested when I open Notes, any button presses in the gamepad will write a letter.

I need to intercept this button presses and run my own functions but unfortunately I am unable to do so.

I've been trying to use GCController but apparently it is not detected as Game Controller object. When I print the count, it shows as 0. My code below.

let gameControllers = GCController.controllers() as! [GCController]
println("configureConnectedGameControllers count: \(gameControllers.count)")

So I assumed it is because the gamepad is detected as bluetooth keyboard that is why its not detected as game controller. And so I attempted to use UIKeyCommand instead. Below is my code:

override func viewDidLoad() {
    super.viewDidLoad()

    var keys = [UIKeyCommand]()
    for digit in "abcdefghijklmnopqrstuvwxyz"
    {
        keys.append(UIKeyCommand(input:  String(digit), modifierFlags: .Command, action:  Selector("keyPressed:")))
        keys.append(UIKeyCommand(input: String(digit), modifierFlags: .Control, action:  Selector("keyPressed:")))
        keys.append(UIKeyCommand(input: String(digit), modifierFlags: nil, action:  "pressKey"))
    }
}

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

func keyPressed(command: UIKeyCommand) {
    println("another key is pressed") //never gets called
}

func pressKey() {
    println("a key is pressed")
}

But even with the above implementation, nothing is printed in the console when i press a button at the gamepad.

This confuses me. So please help me if you know any answer to this. Thanks in advance!


Solution

  • I finally managed to get it working. Below is the code if anyone ever needs it.

    var keys = [UIKeyCommand]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //configureGameControllers()
    
        for digit in "abcdefghijklmnopqrstuvwxyz"
        {
            keys.append(UIKeyCommand(input: String(digit), modifierFlags: nil, action:  Selector("keyPressed:")))
        }
    }
    
    override func canBecomeFirstResponder() -> Bool {
        return true
    }
    
    override var keyCommands: [AnyObject]? {
        get {
            return keys
        }
    }
    
    
    func keyPressed(command: UIKeyCommand) {
        println("user pressed \(command.input)")
    }