13

Is there an API that allows you to determine whether the Apple Pencil is connected to an iPad Pro? Looking over the 9.1 SDK I don't see anything that directly does this. Or perhaps this can be done using the Bluetooth API.

2
  • Did you find anything in the Bluetooth API for this?
    – Rich
    Jan 26, 2016 at 10:20
  • @rich I believe that the only thing you can do is scan the bluetooth devices. But you need BT permission for this. I haven't tried it. Jan 26, 2016 at 17:44

2 Answers 2

7

I can't find any actual documentation on the Apple Pencil's Bluetooth implementation (and I don't believe any exists), but the following code Works for Me™.

It checks for connected devices that advertise themselves as supporting the "Device Information" service and then if any of these have the name "Apple Pencil".

PencilDetector.h

@import CoreBluetooth

@interface PencilDetector : NSObject <CBCentralManagerDelegate>

- (instancetype)init;

@end

PencilDetector.m

#include "PencilDetector.h"

@interface PencilDetector ()

@end

@implementation PencilDetector
{
  CBCentralManager* m_centralManager;
}

- (instancetype)init
{
  self = [super init];
  if (self != nil) {
    // Save a reference to the central manager. Without doing this, we never get
    // the call to centralManagerDidUpdateState method.
    m_centralManager = [[CBCentralManager alloc] initWithDelegate:self
                                                            queue:nil
                                                          options:nil];
  }

  return self;
}

- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
  if ([central state] == CBCentralManagerStatePoweredOn)
  {
    // Device information UUID
    NSArray* myArray = [NSArray arrayWithObject:[CBUUID UUIDWithString:@"180A"]];

    NSArray* peripherals =
      [m_centralManager retrieveConnectedPeripheralsWithServices:myArray];
    for (CBPeripheral* peripheral in peripherals)
    {
        if ([[peripheral name] isEqualToString:@"Apple Pencil"])
        {
            // The Apple pencil is connected
        }
    }
  }
}

@end

In practice, the following, simpler, synchronous code, which doesn't wait for the central manager to be powered on before checking for connected devices seems to work just as well in my testing. However, the documentation states that you shouldn't call any methods on the manager until the state has updated to be CBCentralManagerStatePoweredOn, so the longer code is probably safer.

Anywhere you like

m_centralManager = [[CBCentralManager alloc] initWithDelegate:nil
                                                        queue:nil
                                                      options:nil];

// Device information UUID
NSArray* myArray = [NSArray arrayWithObject:[CBUUID UUIDWithString:@"180A"]];

NSArray* peripherals =
  [m_centralManager retrieveConnectedPeripheralsWithServices:myArray];
for (CBPeripheral* peripheral in peripherals)
{
  if ([[peripheral name] isEqualToString:@"Apple Pencil"])
  {
    // The Apple pencil is connected
  }
}
5
  • 1
    @combinatorial Whoops! Can you tell it's been a while since I've written much Objective-C? ahem. Thanks for the edit!
    – Rich
    Feb 5, 2016 at 10:30
  • What is @"180A"? is it fixed? Apr 4, 2016 at 6:15
  • 2
    @ChandanShettySP @"180A" is an NSString corresponding to the the hex value 0x180A, which is the Bluetooth "Assigned Number" or "short UUID" for the "Device Information" service. This is a service that the current Pencil device offers, and it should continue to work in the future as most (or possibly all) Bluetooth devices should offer this service.
    – Rich
    Apr 5, 2016 at 10:42
  • this code is not working if you turn off bluetooth from control center on ios 11 and later, the CBCentralManager will have CBManagerStatePoweredOff state
    – passingnil
    Aug 10, 2018 at 6:44
  • Hmmm - this works only if the device is connected. If separated from the iPad for some time, it loses the connection. In that case, we may want to scan all Bluetooth devices, and this would not work. Jul 19 at 0:56
6

Took me quite a while to figure out that CBCentralManager's centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) is only called when the connection is initiated via its connect(_ peripheral: CBPeripheral, options: [String : Any]? = nil) function (yes, reading the docs helps :]).

Since we have no callback for when devices have been connected to the device through the user (as is the case with Apple Pencil - I'd love to be proven wrong on this one btw), I had to resort to using a timer here.

This is how it works:

When you initialize ApplePencilReachability a timer is setup that checks for the availability of the pencil every second. If a pencil is found the timer gets invalidated, if bluetooth is turned off it also gets invalidated. When it's turned on again a new timer is created.

I am not particularly proud of it but it works :-)

import CoreBluetooth

class ApplePencilReachability: NSObject, CBCentralManagerDelegate {

  private let centralManager = CBCentralManager()
  var pencilAvailabilityDidChangeClosure: ((_ isAvailable: Bool) -> Void)?

  var timer: Timer? {
    didSet {
      if oldValue !== timer { oldValue?.invalidate() }
    }
  }

  var isPencilAvailable = false {
    didSet { 
      guard oldValue != isPencilAvailable else { return }
      pencilAvailabilityDidChangeClosure?(isPencilAvailable)
    }
  }

  override init() {
    super.init()
    centralManager.delegate = self
    centralManagerDidUpdateState(centralManager) // can be powered-on already?
  }
  deinit { timer?.invalidate() }

  func centralManagerDidUpdateState(_ central: CBCentralManager) {
    if central.state == .poweredOn {
      timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { 
        [weak self] timer in // break retain-cycle
        self?.checkAvailability()
        if self == nil { timer.invalidate() }
      }
    } else {
      timer = nil
      isPencilAvailable = false
    }
  }

  private func checkAvailability() {
    let peripherals = centralManager.retrieveConnectedPeripherals(withServices: [CBUUID(string: "180A")])
    let oldPencilAvailability = isPencilAvailable
    isPencilAvailable = peripherals.contains(where: { $0.name == "Apple Pencil" })
    if isPencilAvailable {
      timer = nil // only if you want to stop once detected
    }
  }

}
8
  • Admit it! You just copied the code from over here!!! ;-): gitlab.com/DanielBocksteger/BOApplePencilReachability/blob/…
    – hnh
    Oct 15, 2017 at 10:49
  • Well, that file has a copyright from 2017 so it’s probably the other way around, but nice find, I actually know Daniel :D
    – HAS
    Oct 15, 2017 at 10:50
  • You should probably not compare the peripheral by name, but by looking at a pencil specific service (UUID). You can use the Xcode Bluetooth tools to browse the services provided.
    – hnh
    Oct 15, 2017 at 10:56
  • Thanks for the pointer @hnh , I don’t have the time currently to look at it, but I’ll write it on my todo list :) (of you already have a solution please feel free to edit the code :))
    – HAS
    Oct 15, 2017 at 10:58
  • 2
    You are right. Also, FWIW, all the BT stuff should probably run on a background queue (it could DispatchQueue.main.async the callback). And again, the name comparison is likely a bad idea.
    – hnh
    Oct 15, 2017 at 18:55

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.