KRNBluetoothKit 是一个用于通过 Bluetooth 4.0 LE 快速在两个 iOS 蓝牙设备之间进行交互的简单库。配置此库和使用它无需深入了解 CoreBluetooth 框架。Bluetooth 4.0 LE 的规范基于中心设备和外围设备之间的关系。外围设备会广播一些数据,并允许连接。相反,中心设备扫描广播的外围设备,并能够连接它们。KRNBluetoothKit 要求一台 iOS 设备扮演中心设备,而另一台 iOS 设备扮演外围设备。这些设备在连接后的每个设备都能向另一台设备发送 NSData 消息。
自 iOS 10.0 或之后的 iOS 应用程序必须在其 Info.plist 文件中包含需要访问的数据类型的用法描述键,否则它将崩溃。要使用 CoreBluetooth 框架的方法以及相应的 KRNBluetoothKit,您必须将 NSBluetoothPeripheralUsageDescription 键添加到 Info.plist 中(键的类型是字符串),提供的该键的值将作为系统提示用户允许使用蓝牙的警告的一部分显示。
您必须有或创建服务和读写特征的 UUID 字符串。这些值必须在初始化中心或外围管理器时通过 initWithServiceUUID:writeCharacteristicUUID:andReadCharacteristicUUID 方法传递。
要创建 UUID 代码,请在您的 macOS 中打开终端,并使用命令“uuidgen”生成新的、具有高度可能性的唯一 UUID 代码。如果您还没有 UUID 代码,只需生成三个新代码,并用它进行管理器初始化。您必须对中心和外围管理器使用相同的 UUID 代码。
static NSString* const kServiceUUID = @"BCA96A6D-9128-4B82-AAB1-426323F1A38B";
static NSString* const kWriteCharacteristicUUID = @"0ACAD532-C68A-4BF2-A7A0-7C4448BAECD1";
static NSString* const kReadCharacteristicUUID = @"7BFC528D-1857-4EFE-8C28-392A56176CCD";
…
//iOS device that will play role of peripheral manager
self.peripheralManager = [[KRNPeripheralManager alloc]initWithServiceUUID:kServiceUUID writeCharacteristicUUID:kWriteCharacteristicUUID andReadCharacteristicUUID:kReadCharacteristicUUID];
//iOS device that will play role of central manager
self.centralManager = [[KRNPeripheralManager alloc]initWithServiceUUID:kServiceUUID writeCharacteristicUUID:kWriteCharacteristicUUID andReadCharacteristicUUID:kReadCharacteristicUUID];
如果您希望中心设备能够连接到您的外围设备,您应该开始广播。在开始广播之前,您应该设置用于处理中心设备传入消息的处理程序块。
self.bluetoothManager.getMessageCompletion = ^(NSData *message) {
NSLog(@"Incoming message = %@", message);
//write custom code here to handle and parse incoming message from central device
};
然后,您将使用在远程中心连接后调用的完成处理程序开始广播。
[self.bluetoothManager startAdvertising:^(KRNConnectionState state) {
if (state == KRNConnectionStateConnected) {
// remote central connected
// you are able to send data
}
}];
连接后,使用 sendPacket 方法向中心设备发送数据包。
[self.bluetoothManager sendPacket:somePacket];
中心设备的设置非常简单。
为来自外围设备的传入消息设置处理程序块(类似于步骤2中的外围设备)。
self.bluetoothManager.getMessageCompletion = ^(NSData *message) {
NSLog(@"Incoming message = %@", message);
//write custom code here to handle and parse incoming message from peripheral device
};
在创建并初始化 KRNCentralManager 实例后,设置 getMessageCompletion 处理程序调用下一方法来扫描并连接到步骤2中设置的外围设备。
[self.bluetoothManager scanAndConnectToPeripheral:^(KRNConnectionState state) {
if (state == KRNConnectionStateConnected) {
// connected to remote peripheral
// you are able to send data
}
}];
如果 KRNCentralManager 发现合适的外围设备,它将自动连接。将调用完成。您还可以使用 KVO(键值观察)观察 KRNCentralManager 实例的 connectionState 属性以处理连接状态(连接或未连接)的变化。
使用 sendPacket 方法向外围设备发送数据包。
[self.bluetoothManager sendPacket:somePacket];
KRNBluetoothKit 在 MIT 许可证下发布。请参阅 LICENSE 了解详情。
有任何建议或问题?请创建一个 Github issue 或联系我。