React Native BLE Manager iOS写入数据失败,Android正常求助
React Native BLE Manager:iOS写入数据日志显示成功但无实际输出问题排查
问题场景
React Native开发中使用BLE Manager时,iOS设备调用写入数据方法后日志提示"Write success",但外设无数据输出;Android端相同代码逻辑运行完全正常,且iOS端的BLE扫描、连接、读取、通知功能均正常,调整MTU大小后问题依旧。
相关代码
BLE Helper中的write方法
write(data, serviceId, characteristicId) { return new Promise((resolve, reject) => { BleManager.retrieveServices(this.peripheralId) .then(() => { console.log("writing data --->: ", data); BleManager.writeWithoutResponse(this.peripheralId, serviceId, characteristicId, data, data.length) .then(() => { console.log('Write success in helper: ', data.toString()); resolve(); }) .catch((error) => { console.log('Write failed: ', error); reject(error); }); }) .catch((error) => { console.log('Write failed: ', error); reject(error); }) }); }
调用写入方法的业务代码
const writecharacteristics = async (serviceUUID1, characteristicUUID1) => { setWritingData(true); setTimeout(() => { setWritingData(false); }, 2000); const minimum1Hex = minimum1.toString(16); const maximum1Hex = maximum1.toString(16); const editedData = minimum1Hex + maximum1Hex; const finalData = '24' + editedData + '23'; const editedDataBytes = []; for (let i = 0; i < finalData.length; i += 2) { const byteValue = parseInt(finalData.substr(i, 2), 16); editedDataBytes.push(byteValue); } console.log('editedDataBytes for Auto height-------------->', editedDataBytes); await BluetoothManager.write(editedDataBytes, serviceUUID1, characteristicUUID1) .then((written) => {}) .catch((error) => { console.log('Error writing data:', error); }); };
日志输出
LOG editedDataBytes for Auto height---------------> [36, 22, 44, 35] LOG < ------- This is what i am writing------> LOG < ------- this.peripheralId------> 9a ************** LOG < ------- serviceId------> c **************** LOG < ------- characteristicId------> c1a *************** LOG < ------- data------> [36, 22, 44, 35] LOG < ------- data.length, ------> 4 LOG < ------- This is what i am writing------> LOG < ------- This is what i am writing------> LOG Write success in helper: 36, 22, 44, 35
解决方案
- 检查特征值属性兼容性:iOS对
writeWithoutResponse的校验更严格,确认目标特征值是否支持Write Without Response(BLE属性标识为0x04)。如果特征值仅支持带响应的Write(0x08),将BleManager.writeWithoutResponse替换为BleManager.write(带响应写入),iOS会等待外设的响应确认,避免静默失败。 - 统一数据类型为Uint8Array:iOS的BLE栈对数据类型要求更严格,将普通数组转换为
Uint8Array后再传入写入方法:// 修改数据构建逻辑 const uint8Data = new Uint8Array(editedDataBytes); await BluetoothManager.write(uint8Data, serviceUUID1, characteristicUUID1); - 缓存服务信息,避免重复调用retrieveServices:当前write方法每次写入都调用
retrieveServices,iOS频繁调用可能导致BLE栈状态异常。建议在设备连接成功后一次性获取服务并缓存,写入时直接使用缓存的服务/特征值信息。 - 验证iOS BLE权限配置:确保
Info.plist中添加了正确的权限描述:<key>NSBluetoothAlwaysUsageDescription</key> <string>需要蓝牙权限连接外设</string> <key>NSBluetoothPeripheralUsageDescription</key> <string>需要蓝牙权限连接外设</string> - 查看底层CoreBluetooth日志:在Xcode的
Debug > OS Log中搜索CoreBluetooth,查看BLE写入的底层交互日志,确认数据是否真正发送,或是否存在底层报错信息。
内容的提问来源于stack exchange,提问作者Hamza Qayyum
相关产品推荐
相关产品推荐

