iOS BLE 开发(Swift 实现 + 面试 + 开发必备)
一、BLE 基础概念必须懂1. BLE 是什么Bluetooth Low Energy低功耗蓝牙特点低功耗、连接快、小数据传输适用于智能硬件、手环、车机、传感器、设备诊断2. BLE 角色Central中心设备手机主动扫描、连接Peripheral外设硬件设备被动广播、被连接3. BLE 通信核心结构外设 → 服务 (Service) → 特征 (Characteristic)Service功能模块UUIDCharacteristic数据通道读写 / 通知所有数据交互都通过Characteristic完成二、iOS BLE 开发完整流程Swift 标准 7 步1. 初始化 CBCentralManagerimportCoreBluetoothclassBLEManager:NSObject,CBCentralManagerDelegate,CBPeripheralDelegate{varcentralManager:CBCentralManager!varconnectedPeripheral:CBPeripheral!overrideinit(){super.init()centralManagerCBCentralManager(delegate:self,queue:.main)}}// 蓝牙状态回调funccentralManagerDidUpdateState(_central:CBCentralManager){ifcentral.state.poweredOn{print(蓝牙已开启可以扫描)}else{print(蓝牙不可用)}}2. 扫描外设// 开始扫描funcstartScan(){guardcentralManager.state.poweredOnelse{return}// 传入 nil 扫描所有设备传入服务 UUID 可精准扫描centralManager.scanForPeripherals(withServices:nil,options:nil)}// 扫描到设备funccentralManager(_central:CBCentralManager,didDiscover peripheral:CBPeripheral,advertisementData:[String:Any],rssiRSSI:NSNumber){print(发现设备\(peripheral.name??未知设备))// 记录设备、停止扫描、准备连接}// 停止扫描funcstopScan(){centralManager.stopScan()}3. 连接外设funcconnect(peripheral:CBPeripheral){connectedPeripheralperipheral connectedPeripheral.delegateselfcentralManager.connect(peripheral,options:nil)}// 连接成功funccentralManager(_central:CBCentralManager,didConnect peripheral:CBPeripheral){print(连接成功)// 连接后自动搜索服务peripheral.discoverServices(nil)}// 连接失败funccentralManager(_central:CBCentralManager,didFailToConnect peripheral:CBPeripheral,error:Error?){print(连接失败\(error?.localizedDescription??))}4. 发现服务funcperipheral(_peripheral:CBPeripheral,didDiscoverServices error:Error?){guardletservicesperipheral.serviceselse{return}forserviceinservices{// 发现特征peripheral.discoverCharacteristics(nil,for:service)}}5. 发现特征funcperipheral(_peripheral:CBPeripheral,didDiscoverCharacteristicsFor service:CBService,error:Error?){guardletcharacteristicsservice.characteristicselse{return}forcharacincharacteristics{print(特征UUID\(charac.uuid))// 可根据 UUID 匹配读写/通知特征}}6. 数据交互核心① 读特征funcreadCharacteristic(_charac:CBCharacteristic){connectedPeripheral.readValue(for:charac)}// 读结果回调funcperipheral(_peripheral:CBPeripheral,didUpdateValueFor characteristic:CBCharacteristic,error:Error?){ifletdatacharacteristic.value{letvalueString(data:data,encoding:.utf8)print(读取到数据\(value??))}}② 写特征funcwriteData(_data:Data,to charac:CBCharacteristic){connectedPeripheral.writeValue(data,for:charac,type:.withResponse)}③ 订阅通知硬件主动推送funcsubscribeNotify(_charac:CBCharacteristic){connectedPeripheral.setNotifyValue(true,for:charac)}// 取消订阅funcunsubscribeNotify(_charac:CBCharacteristic){connectedPeripheral.setNotifyValue(false,for:charac)}// 通知数据回调硬件主动发数据funcperipheral(_peripheral:CBPeripheral,didUpdateValueFor characteristic:CBCharacteristic,error:Error?){ifletdatacharacteristic.value{// 处理硬件推送的数据}}7. 断开连接funcdisconnect(){ifletperipheralconnectedPeripheral{centralManager.cancelPeripheralConnection(peripheral)}}// 断开回调funccentralManager(_central:CBCentralManager,didDisconnectPeripheral peripheral:CBPeripheral,error:Error?){print(设备断开连接)// 可在此处执行重连逻辑}三、GATT 机制详解面试必问GATT Generic Attribute ProfileBLE 数据交互的标准协议规则以Service为功能单位以Characteristic为数据单位手机和硬件通过读写 / 通知交互数据Characteristic 三种交互方式Read手机主动读Write手机主动写Notify硬件主动推送给手机最常用四、断连重连机制Swift 最稳定实现1. 监听断开上面已实现2. 重连策略直接用 UUID 重连无需扫描// 存储设备 UUIDletstoredUUIDString设备的identifier.uuidString// 重连方法funcreconnect(){guardletuuidUUID(uuidString:storedUUIDString)else{return}letperipheralscentralManager.retrievePeripherals(withIdentifiers:[uuid])ifletperipheralperipherals.first{connectedPeripheralperipheral connectedPeripheral.delegateselfcentralManager.connect(peripheral,options:nil)}}3. 重连失败 → 延迟重试 / 重新扫描五、iOS 对 BLE 的强限制非常重要1. 扫描限制后台扫描必须指定 Service UUID后台扫描频率降低不能无限扫描2. 连接限制最多同时连接~20 个设备看系统连接失败不会自动重连3. 后台运行限制必须开启Background Modes → Uses Bluetooth LE accessories后台不能长时间扫描后台写数据可能延迟 / 被挂起4. 权限限制iOS 13NSBluetoothAlwaysUsageDescriptioniOS 14NSBluetoothPeripheralUsageDescription不配置权限直接崩溃5. 电池优化限制系统会自动休眠 BLE频繁扫描会导致耗电飙升不用时必须停止扫描6. 系统杀死 APP后台超过一定时间会被系统 kill被杀死后无法自动重连除非重新打开 APP六、iOS BLE 开发注意事项Swift 避坑大全1. 必须判断 CBCentralManager 状态状态未启用就扫描 →直接无效2. 不要连续调用 connect连接中再次 connect → 系统报错加isConnecting标记位3. 订阅通知前必须判断特征属性ifcharac.properties.contains(.notify){// 允许订阅}4. 数据分包发送BLE 单次最大传输20 字节超过必须分包、组包5. 不要阻塞主线程所有 BLE 回调都在子线程UI 更新必须切主线程DispatchQueue.main.async{// 更新 UI}6. 多设备管理用 UUID 作为唯一标识不要用外设对象 / 名称7. 处理设备信号弱信号弱RSSI lt; -80会导致卡顿、断连不要远距离操作8. 释放逻辑页面退出时停止扫描取消连接置空代理防止内存泄漏、崩溃七、面试高频 BLE 问题总结BLE 经典蓝牙区别BLE GATT 结构Characteristic 三种交互方式iOS 后台 BLE 限制断连重连如何实现BLE 数据超过 20 字节怎么办iOS 13 蓝牙权限BLE 开发常见崩溃原因八、一句话总结面试背诵iOS BLE 开发基于GATT 协议流程为初始化 → 扫描 → 连接 → 发现服务 → 发现特征 → 读写 / 通知 → 断开 / 重连。iOS 对扫描、后台、权限、电量都有严格限制开发必须注意线程、分包、重连、内存、权限、后台模式才能保证稳定不崩溃。
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2616162.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!