ios - 无法将数据发送到特征

标签 ios swift bluetooth-lowenergy

当远程设备更改特征值时,我可以在应用程序上收到通知,但是当应用程序更新值时,远程设备将看不到它。

所以,我知道我的特征是有效的,我也知道其他应用能够写回该特征(实际设备打印它)

所以问题当然是 在应用程序中

更有趣的是,每个特征都有 句柄 ,每个句柄都有自己的 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.withResponsewriteValue

关于ios - 无法将数据发送到特征,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39603104/

相关文章:

android - 如何在android中从字符串创建UUID

c# - Windows BluetoothLeAdvertisement 不包含 Android 设备广播的服务 uuid

ios - 从后台更新后从 View 层次结构中删除以前的 View Controller

ios - 类似于 Whatsapp 的已读状态的双复选标记

ios - 从 iOS 应用程序将视频上​​传到 youtube 返回 400

swift - 你能在 swift 中强制使用类型别名吗

ios - BLE和ANCS自动连接场景

ios - 如何将异步方法变成同步方法

html - 如何在 Objective-C 中解析字符串

ios - 自定义标注 View 内的按钮没有响应(Swift)