You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

寻求Swift 3.0中替代JavaScript getUint16的BLE数据解析方案

等效的Swift 3.0 BLE数据解析实现

你的JavaScript代码核心是读取指定BLE服务和特征的数据,用小端序解析出6个Uint16值,再赋值给对应页面元素。下面是Swift 3.0的等效实现,重点解决如何从CBCharacteristic.value中提取UInt16类型的数据:

核心解析逻辑

在Swift中,BLE特征的value是Data类型,我们可以通过withUnsafeBytes安全访问原始字节,再结合小端序转换来匹配JS里的getUint16(..., true)行为。

完整代码示例

假设你已经通过BLE连接拿到了目标CBPeripheral和CBCharacteristic,可以这样实现:

// 首先处理BLE特征值更新的回调(通常在CBPeripheralDelegate方法中)
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
    // 先处理错误情况,对应JS里的app.OnError
    if let error = error {
        print("BLE读取失败: \(error.localizedDescription)")
        // 这里可以替换成你的错误处理逻辑,比如弹出提示
        return
    }
    
    // 确认当前特征是你要读取的目标特征
    let targetCharUUID = CBUUID(string: "4914140b-61EE-46BF-858C-6872C0C9A710")
    guard characteristic.uuid == targetCharUUID else {
        return
    }
    
    // 确保数据不为空且长度符合预期(6个UInt16共12字节)
    guard let data = characteristic.value, data.count >= 12 else {
        print("无效的BLE数据")
        return
    }
    
    // 按小端序逐个提取UInt16值
    let profile71 = data.subdata(in: 0..<2).withUnsafeBytes {
        $0.load(as: UInt16.self).littleEndian
    }
    let profile72 = data.subdata(in: 2..<4).withUnsafeBytes {
        $0.load(as: UInt16.self).littleEndian
    }
    let profile73 = data.subdata(in: 4..<6).withUnsafeBytes {
        $0.load(as: UInt16.self).littleEndian
    }
    let profile74 = data.subdata(in: 6..<8).withUnsafeBytes {
        $0.load(as: UInt16.self).littleEndian
    }
    let profile75 = data.subdata(in: 8..<10).withUnsafeBytes {
        $0.load(as: UInt16.self).littleEndian
    }
    let profile76 = data.subdata(in: 10..<12).withUnsafeBytes {
        $0.load(as: UInt16.self).littleEndian
    }
    
    // 更新UI必须回到主线程(Swift中UI操作不能在后台线程执行)
    DispatchQueue.main.async {
        // 假设你的UI元素是IBOutlet,比如UITextField或UILabel
        self.profile71TextField.text = "\(profile71)"
        self.profile72TextField.text = "\(profile72)"
        self.profile73TextField.text = "\(profile73)"
        self.profile74TextField.text = "\(profile74)"
        self.profile75TextField.text = "\(profile75)"
        self.profile76TextField.text = "\(profile76)"
    }
}

关键细节说明

  • 字节序匹配:JS里getUint16(index, true)表示使用小端序解析,Swift中通过.littleEndian转换来保证解析结果和JS完全一致。
  • 安全检查:先判断data是否为空、长度是否足够,避免因数据异常导致崩溃,对应JS里的错误回调逻辑。
  • UI更新线程:Swift中所有UI操作必须在主线程执行,所以用DispatchQueue.main.async包裹UI赋值代码,这和JS直接操作DOM的场景不同。

内容的提问来源于stack exchange,提问作者migro1982

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:46:19