iOS 14中didUpdateValueForCharacteristic未触发问题(Swift5迁移)
针对Swift 5迁移后BLE Notify订阅成功但didUpdateValueForCharacteristic不触发的问题,结合代码和场景,给出以下排查修复步骤:
修正订阅逻辑的变量错误
你代码中didDiscoverCharacteristicsFor方法里,判断Notify属性时错误使用了transferCharacteristic而非当前遍历的characteristic,这会导致订阅逻辑失效。修正代码如下:if characteristic.properties.contains(.notify) { print("\(characteristic.uuid.uuidString): properties contains .notify") // 若需保存目标特征,在此处赋值transferCharacteristic transferCharacteristic = characteristic peripheral.setNotifyValue(true, for: characteristic) }确保CBPeripheral代理正确设置
在设备连接成功的代理方法centralManager(_:didConnect:)中,必须明确设置外设的代理:func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) { peripheral.delegate = self peripheral.discoverServices(nil) }Swift版本迁移后,若代理设置被遗漏或位置错误,会导致后续代理方法无法触发。
验证特征UUID匹配正确性
在didUpdateValueForCharacteristic的switch判断中,确保aCBUUID、bCBUUID、f这些常量是正确的CBUUID实例,Swift 5中建议用字符串初始化:let targetUUID = CBUUID(string: "你的特征UUID字符串")同时打印
characteristic.uuid.uuidString,确认与代码中判断的UUID完全一致(注意大小写和格式)。检查iOS后台模式配置(若需后台运行)
若APP需要在后台接收BLE数据,确认Info.plist中已添加bluetooth-central后台模式,避免迁移后配置丢失导致后台无法接收数据。优化服务与特征发现流程
当前代码在didDiscoverServices中遍历所有服务并立即触发特征发现,可能引发并发问题。可尝试先处理单个服务,验证功能正常后再扩展:func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) { guard let services = peripheral.services else { return } if let targetService = services.first(where: { $0.uuid == targetServiceUUID }) { peripheral.discoverCharacteristics(nil, for: targetService) } }
内容的提问来源于stack exchange,提问作者Khurram awan

