iOS蓝牙断线如何自动重连?CoreBluetooth开发实战教程
环境配置
importCoreBluetoothclassBluetoothManager:NSObject,CBCentralManagerDelegate{varcentralManager:CBCentralManager!varconnectedPeripheral:CBPeripheral?overrideinit(){super.init()centralManager=CBCentralManager(delegate:self,queue:nil)}funccentralManagerDidUpdateState(_central:CBCentralManager){switchcentral.state{case.poweredOn:scanForDevices()case.poweredOff:print("蓝牙未开启")default:break}}}
设备扫描与过滤
funcscanForDevices(){//筛选心率监测设备letheartRateServiceUUID=CBUUID(string:"180D")centralManager.scanForPeripherals(withServices:[heartRateServiceUUID],options:[CBCentralManagerScanOptionAllowDuplicatesKey:false])}funccentralManager(_central:CBCentralManager,didDiscoverperipheral:CBPeripheral,advertisementData:[String:Any],rssiRSSI:NSNumber){guardletname=peripheral.name,name.contains("HRM")else{return}connectedPeripheral=peripheralcentralManager.connect(peripheral,options:nil)}
设备连接与服务发现
funccentralManager(_central:CBCentralManager,didConnectperipheral:CBPeripheral){peripheral.delegate=selfperipheral.discoverServices(nil)//发现所有服务}//CBPeripheralDelegatefuncperipheral(_peripheral:CBPeripheral,didDiscoverServiceserror:Error?){guardletservices=peripheral.serviceselse{return}forserviceinservices{print("发现服务:(service.uuid)")peripheral.discoverCharacteristics(nil,for:service)}}
数据传输处理
funcperipheral(_peripheral:CBPeripheral,didDiscoverCharacteristicsForservice:CBService,error:Error?){guardletcharacteristics=service.characteristicselse{return}forcharacteristicincharacteristics{//订阅心率测量特征ifcharacteristic.uuid==CBUUID(string:"2A37"){peripheral.setNotifyValue(true,for:characteristic)}//读取设备信息ifcharacteristic.uuid==CBUUID(string:"2A29"){peripheral.readValue(for:characteristic)}}}funcperipheral(_peripheral:CBPeripheral,didUpdateValueForcharacteristic:CBCharacteristic,error:Error?){guardletdata=characteristic.valueelse{return}switchcharacteristic.uuid{caseCBUUID(string:"2A37"):letheartRate=parseHeartRate(data)print("当前心率:(heartRate)bpm")caseCBUUID(string:"2A29"):letmodel=String(data:data,encoding:.utf8)print("设备型号:(model??"")")default:break}}
关键问题解决方案
后台运行支持
在Info.plist中添加:
<key>UIBackgroundModes</key><array><string>bluetooth-central</string></array>
连接优化策略
//断线自动重连funccentralManager(_central:CBCentralManager,didDisconnectPeripheralperipheral:CBPeripheral,error:Error?){ifletperipheral=connectedPeripheral{centralManager.connect(peripheral,options:nil)}}//连接超时处理DispatchQueue.main.asyncAfter(deadline:.now()+10.0){ifself.connectedPeripheral?.state!=.connected{self.centralManager.cancelPeripheralConnection(peripheral)}}
数据分包处理
//处理长数据分包varpacketBuffer=Data()funcperipheral(_peripheral:CBPeripheral,didUpdateValueForcharacteristic:CBCharacteristic,error:Error?){guardletdata=https://idctop.com/article/characteristic.valueelse{return}>
安全实践建议
-
配对加密
//请求配对peripheral.openL2CAPChannel(PSM:31)//PSM需根据设备协议指定
-
数据验证
funcvalidateChecksum(_data:Data)->Bool{varchecksum:UInt8=0data.dropLast().forEach{checksum^=$0}returnchecksum==data.last}
-
权限管理
//在Info.plist中配置<key>NSBluetoothAlwaysUsageDescription</key><string>需要蓝牙权限连接健康设备</string>
性能优化技巧
-
连接参数协商
letconnectionOptions:[String:Any]=[CBConnectPeripheralOptionNotifyOnConnectionKey:true,CBConnectPeripheralOptionNotifyOnDisconnectionKey:true,CBConnectPeripheralOptionNotifyOnNotificationKey:true]centralManager.connect(peripheral,options:connectionOptions)
-
动态扫描策略
//根据电量调整扫描间隔funcadjustScanRate(batteryLevel:Float){centralManager.stopScan()letinterval=batteryLevel>0.2?5.0:30.0Timer.scheduledTimer(withTimeInterval:interval,repeats:true){_inself.centralManager.scanForPeripherals(withServices:nil)}}
实战经验分享
-
设备兼容性处理
//双模蓝牙适配#ifos(iOS)letmanager=CBCentralManager(delegate:self,queue:nil)#elseifos(macOS)letmanager=CBCentralManager(delegate:self,queue:nil,options:[CBCentralManagerOptionShowPowerAlertKey:true])#endif
-
错误诊断代码
funcperipheral(_peripheral:CBPeripheral,didWriteValueForcharacteristic:CBCharacteristic,error:Error?){ifleterror=erroras?CBError{switcherror.code{case.writeNotPermitted:print("写入权限被拒绝")case.invalidHandle:print("无效的特征句柄")default:print("未知错误:(error.localizedDescription)")}}}
测试提示:使用Apple的BluetoothExplorer工具(需下载Apple附加工具)模拟BLE设备进行全流程测试。