ios - swift3 中的数据到 Int/String

标签 ios swift bluetooth-lowenergy core-bluetooth

我正在使用 BLE 设备。设备正在发送特定 UUID 中的值。
这是我将 Data 转换为 Int 或 String 以便显示的代码。

...
else if characteristic.uuid == CBUUID(string: UUID_CHANGEIN_BATTERY_LEVEL) {
//            let battery = UInt32(bigEndian: ((characteristic.value?.withUnsafeBytes { $0.pointee }) ?? 0))
            let array : [UInt8] = [0, 0, 0]
            var data = Data(bytes: array)
            if characteristic.value != nil {
                data.append(characteristic.value!)
            }
            let battery = UInt32(bigEndian: ((data.withUnsafeBytes { $0.pointee }) ?? 0))
            print("battery level changed\nNew level is \(getInt(fromData: characteristic.value!, start: 0))!")
//            lblBattery.text = (String(data: characteristic.value!, encoding: String.Encoding.utf8) ?? "0") + "%"
            lblBattery.text = "\(getInt(fromData: characteristic.value!, start: 0))%"

        }
...
func getInt(fromData data: Data, start: Int) -> Int32 {
        let intBits = data.withUnsafeBytes({(bytePointer: UnsafePointer<UInt8>) -> Int32 in
            bytePointer.advanced(by: start).withMemoryRebound(to: Int32.self, capacity: 4) { pointer in
                return pointer.pointee
            }
        })
        return Int32(bigEndian: intBits)
//        return Int32(littleEndian: intBits)
    }

我已检查 BLE 扫描仪 iOS 应用程序,该应用程序显示 0x2b01 作为值,并且还显示 43 作为电池百分比。
我写了 3-4 种代码,如上面所示。 但他们都没有给我 43 作为值。

请帮助我找出哪里做错了或者我缺少哪些内容来满足我的要求。

最佳答案

swift 3

func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {

   let value = [UInt8](characteristic.value!)

   print("Battery ", value[0], "%")
}

关于ios - swift3 中的数据到 Int/String,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47036798/

相关文章:

ios - Swift UIModalPresentationStyle.PageSheet

ios - 解析复杂 JSON 数组的有效方法

objective-c - 在 View Controller 之间传递图像

ios - 滚动时 UISwitch 正在更改其他单元格上的状态

ios - 在 Apple Swift 中,在什么情况下我不想要隐式解包的可选项?

core-bluetooth - CoreBluetooth 事件后台 - iOS 6.0.1 及更高版本中没有事件

ios - 在 UIContainerView swift ios 中调整 subview Controller 的大小

iOS 人脸检测位置

java - 如何设置字节中的特定位以进行 BLE 数据传输?

c - Bluez BLE 连接 Linux