检测Apple Pencil是否已连接到iPad Pro [英] Detect whether Apple Pencil is connected to an iPad Pro
问题描述
是否有API可以让您确定Apple Pencil是否已连接到iPad Pro?查看9.1 SDK我没有看到任何直接这样做的东西。或许这可以使用蓝牙API完成。
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.
推荐答案
我找不到关于Apple Pencil的蓝牙的任何实际文档b $ b实现(我不相信任何存在),但以下代码为我和交易工作
;。
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™.
它检查广告的连接设备他们自己支持
设备信息服务,然后如果其中任何一个名称为Apple
Pencil。
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".
@import CoreBluetooth
@interface PencilDetector : NSObject <CBCentralManagerDelegate>
- (instancetype)init;
@end
PencilDetector.m
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
实际上,以下更简单的同步代码,在检查连接设备
之前不等待
中央管理器开机在我的测试中同样工作。但是,文档说明你不应该
调用管理器上的任何方法,直到状态更新为
CBCentralManagerStatePoweredOn
,所以代码越长可能更安全。
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.
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
}
}
这篇关于检测Apple Pencil是否已连接到iPad Pro的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!