【问题标题】:iOS/Swift/CoreBluetooth Ble Notifications not workingiOS/Swift/CoreBluetooth Ble 通知不起作用
【发布时间】:2018-07-09 16:24:57
【问题描述】:

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

我有什么遗漏吗?

提前致谢!

【问题讨论】:

    标签: ios swift bluetooth notifications bluetooth-lowenergy


    【解决方案1】:

    除非您致电didWriteValueFor,否则您不会观察到您的值是否发生变化。

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

    【讨论】:

      猜你喜欢
      • 2023-04-03
      • 1970-01-01
      • 2019-06-22
      • 1970-01-01
      • 2017-06-16
      • 1970-01-01
      • 2020-10-08
      • 2019-02-08
      • 1970-01-01
      相关资源
      最近更新 更多