我正在使用 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/