当远程设备更改特征值时,我可以在应用程序上收到通知,但是当应用程序更新值时,远程设备将看不到它。
所以,我知道我的特征是有效的,我也知道其他应用能够写回该特征(实际设备打印它)
所以问题当然是 在应用程序中。
更有趣的是,每个特征都有 句柄 ,每个句柄都有自己的 UUID。
iOS 只会让我看到我的特征 UUID,无法访问它的句柄,尽管每个特征有 2 个句柄,具有不同的 UUID
无论如何,我在这里得到回调并尝试回信:
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
print("UPDATE FROM:" , characteristic) //good!
sendData(data: "check") //not good
if characteristic.uuid.uuidString == characteristicUUID {
if let str = NSString(data: characteristic.value!, encoding: String.Encoding.utf8.rawValue)
{
print("BLE:GOT:",str )
NotificationCenter.default.post(name: Notification.Name(rawValue: "Bluetooth"), object: str)
}
}
}
和写作:
func sendData(data:String)
{
if(peripheral != nil)
{
//happens for sure
var bytesData = [UInt8](data.utf8)
let writeData = NSData (bytes: &bytesData, length: bytesData.count)
peripheral.writeValue(writeData as Data, for: characteristic, type: CBCharacteristicWriteType.withResponse)
}
}
并列出我的特征(打印 1 个 UUID - 没错,我们只有 1 个,但它有 2 个具有不同 UUID 的句柄)
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
for charateristic in service.characteristics!
{
print("Found CHARACTERISTIC:",charateristic as CBCharacteristic)
}
最佳答案
您应该检查为您的特征设置了哪些属性。如果设置了 CBCharacteristicPropertyWrite
,则可以执行带有响应的写入。如果仅设置了 CBCharacteristicPropertyWriteWithoutResponse
,则您无法执行设置了 type: CBCharacteristicWriteType.withResponse
的 writeValue
。
关于ios - 无法将数据发送到特征,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39603104/