iOS / Swift / CoreBluetooth Ble通知不起作用

时间:2018-07-09 16:24:58

标签: ios swift bluetooth notifications bluetooth-lowenergy

我有一个问题,我连接到外设并将正确的notify值设置为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)
            }
        }

有什么我想念的吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

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

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

        }
 }