核心蓝牙:在WriteValue()之后未调用didWriteValueFor()

2022-09-05 00:00:00 ios swift core-bluetooth

根据Apple开发人员文档,函数didWriteValueFor()是在调用WriteValue()函数之后调用的。(参见https://developer.apple.com/documentation/corebluetooth/cbperipheraldelegate/1518823-peripheral)

我有一个可写的特征,我查找了https://developer.apple.com/documentation/corebluetooth/cbcharacteristicproperties/1519089-write中提到的属性

现在,当我调用WriteValue()函数时,从来没有调用过didWriteValueFor()函数,为什么?我认为它的结构与调用didUpdateValueFor()函数的readValue()函数相同,这对我来说工作得很好。 以下是我的代码:

        func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
    for characteristic in service.characteristics!{
        print(characteristic)
        if(characteristic.uuid == TX_CHARACTERISTIC){
            elsa.writeValue(dataWithHexString(hex: VALID_GET_VERSION_REQUEST), for: characteristic, type: CBCharacteristicWriteType.withResponse)//calls didWriteValueFor if Type = withResponse
        }
        if(characteristic.uuid == RX_CHARACTERISTIC){
            elsa.setNotifyValue(true, for: characteristic)//calls didUpdateNotificationStateFor
        }
    }
}

func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {
    guard let data = characteristic.value else { return }
    print("
Value: (data.toHexEncodedString()) 
was written to Characteristic:
(characteristic)")
    if(error != nil){
        print("
Error while writing on Characteristic:
(characteristic). Error Message:")
        print(error as Any)
    }
}

解决方案

如@Paulw11所述,只有在显式读取该值之后才会写入该值。我通过在didWite()函数中调用一个readValue()修复了这个问题。

更新的解决方案:

func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {
    elsa.readValue(for: characteristic)
    guard let data = characteristic.value else { return }
    print("
Value: (data.toHexEncodedString()) 
was written to Characteristic:
(characteristic)")
    if(error != nil){
        print("
Error while writing on Characteristic:
(characteristic). Error Message:")
        print(error as Any)
    }
}

相关文章