CoreBluetooth:在writeValue()之后不调用didWriteValueFor()

问题描述 投票:1回答:2

根据Apple Developer Documentation,在调用writeValue()函数之后调用函数didWriteValueFor()。 (见https://developer.apple.com/documentation/corebluetooth/cbperipheraldelegate/1518823-peripheral

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

现在当我调用writeValue()函数时,从未调用didWriteValueFor()函数,为什么?我认为它与readValue()函数的结构相同,它调用了didUpdateValueFor()函数,这对我来说很好。这是我的代码:

        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("\nValue: \(data.toHexEncodedString()) \nwas written to Characteristic:\n\(characteristic)")
    if(error != nil){
        print("\nError while writing on Characteristic:\n\(characteristic). Error Message:")
        print(error as Any)
    }
}
ios swift core-bluetooth
2个回答
0
投票

正如@Paulw11所提到的,该值仅在明确读取后才写入。我通过调用didWrite()函数中的readValue()来解决这个问题。


0
投票

当您调用writeValue()时,您可以指定是否需要远程设备的响应。在您的情况下,您指定了CBCharacteristicWriteType.withResponse,它告诉远程设备它需要发回一个响应并指示写入是否成功。当远程设备发送响应消息时,这将触发对didWriteValueFor()的调用。如果您的设备没有发送响应,则不会调用didWriteValueFor()。你可以在apple documentation here上读到这个。您需要运行蓝牙嗅探器捕获来确认这一点,但我怀疑您的蓝牙设备没有正确响应writeValue()请求。

请注意,每个BLE特征都有一组属性,用于控制特征的行为方式。其中一些属性包括:后退,写入,无响应写入,通知,通知。检查您正在使用的特性的属性,并确保它支持'write'属性。如果您的特性支持“无响应写入”但不支持“写入”,那么您的设备将不会将所需消息发送回您的应用程序,因此不会调用didWriteValuefor()。通常,您可以在文档中找到它,或使用蓝牙应用程序(如“LightBlue Explorer”)查看设备的此信息。

© www.soinside.com 2019 - 2024. All rights reserved.