【发布时间】:2018-09-03 10:13:22
【问题描述】:
根据 Apple Developer Documentation,函数 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("\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)
}
}
【问题讨论】:
-
在我的脑海中,据我所知,
didWrite被称为从特征中读取的值,所以如果没有读取,didWrite不会被调用......我很容易将其与另一种情况混为一谈,但这让我感到惊讶 - 这有点像如果您有多个想要写入特征的东西,didWrite是 API 告诉您可以写入下一个值的方式 -
设置断点,但我怀疑您的
guard语句正在返回,因为写入特征的值将是nil;向特征写入值不会更新其value。 -
@Paulw11“将值写入特征不会更新其值”你是什么意思?您的建议是正确的,它在警卫处返回,但是当我随后读取特征的值时,它已成功写入,那么此时它怎么可能为零?
-
我的意思是对
CBCharacteristic实例执行写入不会更新该实例的value属性。您必须明确读取要更新的value属性的特征。仅仅因为您将值“X”写入特征并不意味着它仍然具有该值,因此您必须显式读取它以获取该值。 -
@Paulw11 你能看看stackoverflow.com/q/68409316/14414215 即使明确读取值(使用示例解决方案),值仍然是
null。有趣的是,在 iOS12 上返回了一个值,而在 iOS14 上没有返回值
标签: ios swift core-bluetooth