39
votes

Previous to iOS 9, the most reliable method of determining whether an external keyboard is connected was to listen for UIKeyboardWillShowNotification and make a text field the first responder, as discussed in this question. The notification would fire when using the virtual keyboard, but would not fire when using an external keyboard.

However this behavior has now changed with iOS 9. UIKeyboardWillShowNotification also fires when an external keyboard is connected, since the new keyboard toolbar is now shown.

It is still possible to detect the keyboard height and make a judgement whether it is the smaller toolbar or the larger virtual keyboard that is being shown. However this method is not reliable since the keyboard height has changed between the various beta and can't be counted on to stay the same over time.

Is there a more reliable method that can be used with iOS 9?

9
Just a question. Why do you need to know if a external keyboard is connected?agy
@agy In order to enable functionality that is only supposed to be enabled when the user is using an external keyboard.Sarah Elan
How about this one? github.com/danielamitay/DAKeyboardControl It works with iOS9, but I don't know you can detect if an external keyboard is connected.pixyzehn
I would like to know if a keyboard is attached so I can show keyboard shortcuts (not the ones you get with the command key) — I want to allow typing 1, 2, 3. There would not be a text field.David Dunham

9 Answers

55
votes

After going back to the original question, I've found a solution that works.

It seems that when the regular virtual keyboard is displayed the keyboard frame is within the dimensions of the screen. However when a physical keyboard is connected and the keyboard toolbar is displayed, the keyboard frame is located offscreen. We can check if the keyboard frame is offscreen to determine if the keyboard toolbar is showing.

Objective-C

- (void) keyboardWillShow:(NSNotification *)notification {
    NSDictionary* userInfo = [notification userInfo];
    CGRect keyboardFrame = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGRect keyboard = [self.view convertRect:keyboardFrame fromView:self.view.window];
    CGFloat height = self.view.frame.size.height;

    if ((keyboard.origin.y + keyboard.size.height) > height) {
        self.hasKeyboard = YES;
    }
}

Swift

@objc func keyboardWillShow(_ notification: NSNotification) {
    guard let userInfo = notification.userInfo else {return}
    let keyboardScreenEndFrame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
    let keyboard = self.view.convert(keyboardScreenEndFrame, from: self.view.window)
    let height = self.view.frame.size.height
    if (keyboard.origin.y + keyboard.size.height) > height {
        self.hasKeyboard = true
    }
}
10
votes

iOS 14 SDK finally brings public API for that: GCKeyboard. To check if external keyboard is connected:

let isKeyboardConnected = GCKeyboard.coalesced != nil

Notes:

  • import GameController
  • you might need to enclose it in if #available(iOS 14.0, *)
5
votes

This code supports iOS 8 and iOS 9, inputAccessoryView, has double-protected constant to be ready for new changes in future versions of iOS and to support new devices:

#define gThresholdForHardwareKeyboardToolbar 160.f // it's minimum height of the software keyboard on non-retina iPhone in landscape mode

- (bool)isHardwareKeyboardUsed:(NSNotification*)keyboardNotification {
    NSDictionary* info = [keyboardNotification userInfo];
    CGRect keyboardEndFrame;
    [[info valueForKey:UIKeyboardFrameEndUserInfoKey] getValue:&keyboardEndFrame];
    float height = [[UIScreen mainScreen] bounds].size.height - keyboardEndFrame.origin.y;
    return height < gThresholdForHardwareKeyboardToolbar;
}

Note, a hardware keyboard may present but not used.

2
votes

I am using a variation on Sarah Elan's answer. I was having issues with her approach in certain views. I never quite got to the bottom of what caused the problem. But here is another way to determine if it is an ios9 external keyboard 'undo' bar that you have, rather than the full sized keyboard.

It is probably not very forward compatible since if they change the size of the undo bar, this brakes. But, it got the job done. I welcome criticism as there must be a better way...

//... somewhere ...
#define HARDWARE_KEYBOARD_SIZE_IOS9 55 
//

+ (BOOL) isExternalKeyboard:(NSNotification*)keyboardNotification {

  NSDictionary* info = [keyboardNotification userInfo];
  CGRect keyboardEndFrame;
  [[info valueForKey:UIKeyboardFrameEndUserInfoKey] getValue:&keyboardEndFrame];
  CGRect keyboardBeginFrame;
  [[info valueForKey:UIKeyboardFrameBeginUserInfoKey] getValue:&keyboardBeginFrame];

  CGFloat diff = keyboardEndFrame.origin.y - keyboardBeginFrame.origin.y;
  return fabs(diff) == HARDWARE_KEYBOARD_SIZE_IOS9;
}
1
votes

Private API solution: (have to grab the private header file - use RuntimeViewer).

Works nicely for enterprise apps, where you don't have AppStore restrictions.

#import "UIKit/UIKeyboardImpl.h"

+ (BOOL)isHardwareKeyboardMode
{
   UIKeyboardImpl *kbi = [UIKeyboardImpl sharedInstance];
   BOOL externalKeyboard = kbi.inHardwareKeyboardMode;
   NSLog(@"Using external keyboard? %@", externalKeyboard?@"YES":@"NO");
   return externalKeyboard;
}
0
votes

If you make the toolbar irrelevant then the keyboard doesn't show up. Do this by blanking out its left and right groups (at least on iOS 12.4):

textField.inputAssistantItem.leadingBarButtonGroups = []
textField.inputAssistantItem.trailingBarButtonGroups = []

...and in case it helps here is a swifty way to observe:

// Watch for a soft keyboard to show up
let observer = NotificationCenter.default.addObserver(forName: UIWindow.keyboardWillShowNotification, object: nil, queue: nil) { notification in
    print("no external keyboard")
}

// Stop observing shortly after, since the keyboard should have shown by now
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
    NotificationCenter.default.removeObserver(observer)
}
0
votes
  1. None of the answers here worked for me. I have iPad Air with iOS 13.x.

I was able to do it, I reckon, by checking the height of the keyboard. That's it! Notice when an external keyboard is connected, the onscreen keyboard is about 50-60px in height. See the working demo here: https://youtu.be/GKi-g0HOQUc

So in your event keyboardWillShow, just get the keyboard height and see if it's around 50-60, if so, then we can assume that there's an external keyboard connected.

@objc func keyboardWillShow(_ notification: NSNotification) {
        guard let userInfo = notification.userInfo else {return}
        let keyboardScreenEndFrame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        let keyboard = self.view.convert(keyboardScreenEndFrame, from: self.view.window)

        // If with keyboard, the onscreen keyboard height is 55.
        // otherwise, the onscreen keyboard has >= 408px in height.
        // The 66 digit came from a Stackoverflow comment that the keyboard height is sometimes around that number.
        if keyboard.size.height <= 66 {
            hasExternalKeyboard = true
        } else {
            hasExternalKeyboard = false
        }
    }
-1
votes

You could try checking for peripherals that are advertising services using Core Bluetooth

CBCentralManager *centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil]; 
[centralManager scanForPeripheralsWithServices:nil options:nil];

And you should implement the delegate:

- (void)centralManager:(CBCentralManager * _Nonnull)central
 didDiscoverPeripheral:(CBPeripheral * _Nonnull)peripheral
     advertisementData:(NSDictionary<NSString *,
                                id> * _Nonnull)advertisementData
                  RSSI:(NSNumber * _Nonnull)RSSI{

}
-1
votes

You can subscribe notification when the external device is connected:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deviceConnected:) name:EAAccessoryDidConnectNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deviceDisconnected:) name:EAAccessoryDidDisconnectNotification object:nil];
[[EAAccessoryManager sharedAccessoryManager] registerForLocalNotifications];

Or just retrieve the list of attached devices:

EAAccessoryManager* accessoryManager = [EAAccessoryManager sharedAccessoryManager];

if (accessoryManager)
{
    NSArray* connectedAccessories = [accessoryManager connectedAccessories];
    NSLog(@"ConnectedAccessories = %@", connectedAccessories);
}