ios - iOS/Swift/CoreBluetooth Ble 通知不起作用
问题描述
我有一个问题,我连接到外围设备并将通知值正确设置为 true,但我无法获取该值。我正在遵循接下来的步骤。
1 - 我连接到外围设备
2 - 我发现服务
3 - 我发现服务的特征
4 - 我为特定特征激活通知
override func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
if characteristic.uuid == historicCharacteristicCBUUID && characteristic.properties.contains(.notify) {
print("\(characteristic.uuid): properties contains .notify")
if hasWritenOnHistoric == false {
peripheral.setNotifyValue(true, for: characteristic)
}
}
}
5 - 我等待委托,然后在特征上写入以告诉外围设备开始发送数据
override func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?) {
print(characteristic)
if error == nil {
print("TRUE")
if characteristic.uuid == historicCharacteristicCBUUID && characteristic.isNotifying == true {
writeOnHistory(peripheral: peripheral, characteristic: characteristic)
} else {
print("no ha cambiado su estado")
}
}
}
6 - 在外围设备上写入
func writeOnHistory(peripheral: CBPeripheral, characteristic: CBCharacteristic) {
if characteristic.uuid == historicCharacteristicCBUUID {
hasWritenOnHistoric = true
var bitesArray: [UInt8] = [0x01, 0x05]
for _ in 1...16 {
bitesArray.append(0x00)
}
print(bitesArray.count)
print(bitesArray)
let data = Data(bytes: bitesArray)
peripheral.writeValue(data, for: characteristic, type: .withResponse)
}
}
7 - 这个委托只被调用一次,并且使用空数据 [0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00](在 Android 中工作正常,从外围设备获取所有数据)
override func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
if let data = characteristic.value {
print(data)
}
}
有什么我想念的吗?
提前致谢!
解决方案
除非您调用 ,否则您不会观察到您的值是否已更改didWriteValueFor
。
func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {
if characteristic.uuid == myCharacteristic {
self.bluetoothManager.readValueForCharacteristic(characteristic: myCharacteristic)
}
}
推荐阅读
- node.js - 从一个接口映射到另一个接口
- sql - 如何在 Grafana 中创建因变量来检查 SQL 代理作业
- java - 仅在一个 JSONPath 表达式中过滤多个字段
- flutter - 渲染库问题捕获的异常
- huggingface-transformers - 如何在 Huggingfaces 中从 CSV 加载自定义数据集
- sql - 使用条件合并过期和更新记录
- python - Css 选择器下拉语言选择器 python
- powerbi - Power BI 和 Snowflake 之间的奇怪行为
- python - 如何在 Snapcraft PyQt5 应用程序中的 Ubuntu Budgie 中显示托盘图标?
- batch-file - 使用 & 批量创建文件