





























在 iOS 开发中,Bluetooth(蓝牙)功能主要通过 CoreBluetooth 框架实现。CoreBluetooth 是 iOS 自带的蓝牙通信框架,常用于 BLE(Bluetooth Low Energy)设备的通信。以下是对 iOS Bluetooth 开发的详细讲解,包括基础概念、开发流程以及常见问题。
CoreBluetooth 是 iOS 提供的蓝牙框架,支持 BLE 功能。它主要包括以下核心类:
中心设备负责扫描和连接蓝牙外围设备。
使用 CBCentralManager 的 scanForPeripherals 方法扫描附近的 BLE 设备。
// 开始扫描设备 func startScanning() { centralManager.scanForPeripherals(withServices: nil, options: nil) } // 发现设备时的回调 func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) { print("发现设备: \(peripheral.name ?? "未知设备")") // 停止扫描并连接设备 centralManager.stopScan() centralManager.connect(peripheral, options: nil) }
当扫描到设备后,可以使用 connect 方法连接设备。
外围设备通过服务和特性提供功能,连接后可以扫描服务和特性以获取具体数据。
特性是服务的具体功能接口,可以通过特性读取数据或写入数据。
在 iOS 13+,必须在 Info.plist 文件中声明蓝牙使用权限:
<key>NSBluetoothAlwaysUsageDescription</key> <string>需要访问蓝牙以连接设备</string>
如果不声明权限,应用可能无法正常扫描设备。
确保蓝牙状态为 .poweredOn 才能开始扫描设备,否则可能会报错。
if centralManager.state != .poweredOn { print("蓝牙未开启,无法扫描设备") }
特性必须支持操作(如 read 或 write),才能与其交互。
if characteristic.properties.contains(.read) { peripheral.readValue(for: characteristic) } else { print("该特性不支持读取操作") }
设备可能会意外断开连接,需要处理断开事件并尝试重新连接。
func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) { print("设备断开连接: \(error?.localizedDescription ?? "未知原因")") // 尝试重新连接 centralManager.connect(peripheral, options: nil) }
withServices 参数指定需要扫描的设备服务 UUID,减少扫描范围。.withoutResponse 写入特性数据时,可提高写入性能,但需确保设备支持无响应写入。此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。