You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift BLE调用discoverServices仅发现数组首个服务的问题

解决蓝牙同时发现多个服务的问题

你的问题出在didDiscoverServices代理方法的for循环里的return语句——处理完第一个服务后就直接退出循环了,第二个服务根本没被遍历到。

看你原来的代码:

for service in services {
    // ...服务判断逻辑
    peripheral.discoverCharacteristics([...], for: service)
    return // 这里直接退出循环了!
}

只要把这个return删掉,循环就能遍历所有已发现的服务,自然就能同时处理BatteryService和NordicUARTService了。

另外可以优化特征发现的逻辑,针对不同服务只搜索对应的特征,避免无效操作:

修正后的完整代码:

func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
    if peripheral == myDevice {
        print("Connected to  \(peripheral.name ?? "") \(peripheral.identifier )\n\n")
        peripheral.discoverServices([bluetoothPeripheral.BatteryService, bluetoothPeripheral.NordicUARTService])
    }
}

// Delegate - Called when services are discovered
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
    if let services = peripheral.services {
        for service in services {
            var targetCharacteristics: [CBUUID] = []
            
            if service.uuid == bluetoothPeripheral.BatteryService{
                print("Battery Service found")
                targetCharacteristics = [bluetoothPeripheral.BatteryLevelChar]
            } else if service.uuid == bluetoothPeripheral.NordicUARTService{
                print("UART Service found")
                targetCharacteristics = [bluetoothPeripheral.RxChar, bluetoothPeripheral.TxChar]
            }
            
            // 只搜索当前服务对应的特征
            if !targetCharacteristics.isEmpty {
                peripheral.discoverCharacteristics(targetCharacteristics, for: service)
            }
        }
    }
}

这样修改后,就能同时发现两个服务及其对应的特征,输出里也会同时出现"Battery Service found"和"UART Service found"的提示。

内容的提问来源于stack exchange,提问作者Intra Preneur

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 12:17:30