读写数据需要考虑具体的使用场景,比如Data,Byte,bit的转换,数据字节序的大小端,数据是否分包。以及对于外设的某些信息的判断:比如说,你要交互的特征,它的properties的值是0x10,表示你只能用订阅的方式来接收数据:
如果properties的值是0x10,在
didDiscoverCharacteristicsForService里写 [peripheral setNotifyValue:YES forCharacteristic:characteristic];
//如果需要更新Characteristic的值
`if (needReadValueForCharacteristic) {
for (CBCharacteristic *characteristic in service.characteristics) {
// [peripheral readValueForCharacteristic:characteristic];
[peripheral setNotifyValue:YES forCharacteristic:characteristic];
//判断读写权限
// if (characteristic.properties & CBCharacteristicPropertyRead ) {
// [peripheral readValueForCharacteristic:characteristic];
// }
}
}`
重连外设(Retrieve)
当外设已处于连接状态,或者与手机配对的状态下,是无法直接通过扫描发现外设的,CoreBluetooth提供了重连恢复的API,它有两种方式,返回值都是外设Peripheral数组:
1.retrievePeripheralsWithIdentifiers,参数是设备的UUID
2.retrieveConnectedPeripheralsWithServices,参数是特定服务的UUID
NSUUID *uuid = [[NSUUID alloc] initWithUUIDString:uuidString1]; [uuidArray addObject:(id)uuid]; if(uuidArray.count != 0) { NSArray * arr = [_bleCentralManager retrievePeripheralsWithIdentifiers:uuidArray]; }