首先,你必须知道你使用了什么样的characteristic properties
。
类型1:CBCharacteristicPropertyNotify
这样,你必须设置为通知特色的服务。
例如:
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(nullable NSError *)error{
if (error) {
NSlog(@"error:%@",error.localizedDescription);
return ;
}
for (CBCharacteristic *characteristic in service.characteristics) {
if (characteristic.properties & CBCharacteristicPropertyNotify) {
[peripheral setNotifyValue:YES forCharacteristic:characteristic];
}
}
}
类型2:CBCharacteristicPropertyRead
或其他
这样,你必须阅读的特征值后发送数据成功。
- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(nullable NSError *)error{
if (error) {
NSlog(@"error:%@",error.localizedDescription);
return ;
}
if (!(characteristic.properties & CBCharacteristicPropertyNotify)) {
[peripheral readValueForCharacteristic:characteristic];
}
}
后,您可以接收数据:
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(nullable NSError *)error{
if (error) {
NSlog(@"error:%@",error.localizedDescription);
return ;
}
NSlog(@"characteristic value = %@",characteristic.value);
uint8_t *data = (uint8_t *)[characteristic.value bytes];
NSMutableString *temStr = [[NSMutableString alloc] init];
for (int i = 0; i < characteristic.value.length; i++) {
[temStr appendFormat:@"%02x ",data[i]];
}
NSlog(@"receive value:%@",temStr);
}
您可能会发现一些帮助,这演示:https://github.com/arrfu/SmartBluetooth-ios-objective-c