Flutter iOS端flutter_blue_plus扫描BLE时出现API误用问题
iOS端BLE扫描问题解决方案
1. 修复API MISUSE警告
日志中出现的API MISUSE: <CBCentralManager: 0x30032d2c0> has no restore identifier but the delegate implements the centralManager:willRestoreState: method警告,可通过以下方式处理:
- 在初始化FlutterBluePlus时,明确禁用状态恢复:
需在调用任何蓝牙操作前执行该配置。FlutterBluePlus.instance.setOptions(restoreState: false);
2. 添加iOS必需的蓝牙权限配置
iOS对蓝牙权限有严格要求,必须在ios/Runner/Info.plist中添加以下配置:
<!-- iOS 13+ 必需的蓝牙权限描述 --> <key>NSBluetoothAlwaysUsageDescription</key> <string>需要蓝牙权限来扫描和连接BLE设备</string> <!-- 兼容iOS 12及以下版本 --> <key>NSBluetoothPeripheralUsageDescription</key> <string>需要蓝牙权限来扫描和连接BLE设备</string> <!-- 若需后台扫描,添加此项 --> <key>UIBackgroundModes</key> <array> <string>bluetooth-central</string> </array>
注意:权限描述需清晰说明用途,否则可能影响App Store审核。
3. 检查扫描逻辑的iOS适配
- 确保在蓝牙状态变为
PoweredOn后再发起扫描,避免状态未就绪时调用:FlutterBluePlus.instance.state.listen((state) { if (state == BluetoothState.on) { // 发起扫描 FlutterBluePlus.instance.startScan(timeout: const Duration(seconds: 5)); } }); - iOS上扫描设备时,若指定服务UUID,需确保格式为小写带连字符的标准格式;扫描所有设备时避免不必要的过滤。
4. 更新插件版本
使用最新版flutter_blue_plus,旧版本可能存在iOS适配bug:
flutter pub upgrade flutter_blue_plus
完成以上配置后重新编译iOS项目,即可解决扫描问题。
内容的提问来源于stack exchange,提问作者Yolo-cell-hash




