首先,你必須知道你使用了什麼樣的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