首页 > 解决方案 > 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)
            }
        }

有什么我想念的吗?

提前致谢!

标签: iosswiftbluetoothnotificationsbluetooth-lowenergy

解决方案


除非您调用 ,否则您不会观察到您的值是否已更改didWriteValueFor

 func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) { 
        if characteristic.uuid == myCharacteristic {
            self.bluetoothManager.readValueForCharacteristic(characteristic: myCharacteristic)

        }
 }

推荐阅读