[iOS] Reading BT keyboard presses

Bluetooth Keyboard ImageThere are times when you’ll want to read key presses coming from a Bluetooth keyboard in your iOS application. This post addresses a technique I’ve come up with to do this

This method uses NSNotificationCenter and a UITextField to do this. A thing to note is that if you don’t have a BT keyboard paired with your iDevice, you’ll get the virtual keyboard to appear. If paired, you won’t see the virtual keyboard, so there is no need to force-hide it or anything like that. If the keyboard becomes unpaired or powers off, you’ll see the virtual keyboard pop up from the bottom.

So we are going to read the single key presses coming into the iOS application (much like we do in Flash… however we don’t get a keyUp, keyDown, etc.)

Place a UITextField in your application via Xcode & declare it in your code (ie. IBOutlet UITextField *textField, etc.)… here is the little crust. This is NOT localized!

#pragma mark - Keyboard

- (void)handle_TextFieldTextChanged:(id)notification {
    NSString *sValue = self.textField.text;
    if([sValue isEqualToString:@"a"]){
        NSLog(@"a was pressed");
    //Avoid a loop for the change, happens even on setting to empty string
    [self.textField resignFirstResponder];
    self.textField.text = @"";
    [self.textField becomeFirstResponder];

- (void)registerForTextFieldNotifications {
    NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
    [notificationCenter addObserver:self
                           selector:@selector (handle_TextFieldTextChanged:)

#pragma mark - View lifecycle

- (void)viewDidLoad {
    [super viewDidLoad];
    self.textField.hidden = YES;
    [self.textField becomeFirstResponder];
    [self registerForTextFieldNotifications];

You can hide the control offscreen. I chose to simply hide it altogether since I used Xcode to place the control and didn’t do it programmatically.

I haven’t done anything in regards to localization and this technique only reads a character at a time without any notion of keyDown and keyUp which would be nice to determine a press and hold using an NSTimer or something like that. The only solution I can think of at the moment would be for a custom keyboard that itself sent the correct character and then followed the release with a custom value used as a delimiter that you could respond to while ignoring it’s actual value. I’ll keep thinking about that bit.

Related Posts Plugin for WordPress, Blogger...

Leave a Reply

Your email address will not be published. Required fields are marked *

1 × = two

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>