核心蓝牙:在WriteValue()之后未调用didWriteValueFor() [英] CoreBluetooth: didWriteValueFor() is not called after writeValue()

查看:0
本文介绍了核心蓝牙:在WriteValue()之后未调用didWriteValueFor()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据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)
    }
}

这篇关于核心蓝牙:在WriteValue()之后未调用didWriteValueFor()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆