iOS应用通过Core Bluetooth框架与低功耗蓝牙设备交互,开发核心是CBCentralManager管理中心设备扫描连接,CBPeripheral处理外设通信,以下是完整实现流程:

环境配置与权限
- 在
Info.plist添加隐私声明:<key>NSBluetoothAlwaysUsageDescription</key> <string>需要蓝牙权限连接智能设备</string> <key>NSBluetoothPeripheralUsageDescription</key> <string>设备需通过蓝牙传输数据</string>
中心模式开发流程
import CoreBluetooth
class BluetoothManager: NSObject {
private var centralManager: CBCentralManager!
private var connectedPeripheral: CBPeripheral?
override init() {
super.init()
centralManager = CBCentralManager(delegate: self, queue: nil)
}
}
// 1. 蓝牙状态检测
extension BluetoothManager: CBCentralManagerDelegate {
func centralManagerDidUpdateState(_ central: CBCentralManager) {
switch central.state {
case .poweredOn:
scanPeripherals()
case .unauthorized:
print("请开启蓝牙权限")
default: break
}
}
// 2. 扫描设备
private func scanPeripherals() {
let serviceUUIDs = [CBUUID(string: "180A")] // 目标设备服务UUID
centralManager.scanForPeripherals(withServices: serviceUUIDs, options: nil)
}
// 3. 发现设备回调
func centralManager(_ central: CBCentralManager,
didDiscover peripheral: CBPeripheral,
advertisementData: [String : Any],
rssi RSSI: NSNumber) {
guard peripheral.name?.contains("MY_DEVICE") == true else { return }
connectedPeripheral = peripheral
central.connect(peripheral, options: nil)
}
// 4. 连接成功
func centralManager(_ central: CBCentralManager,
didConnect peripheral: CBPeripheral) {
peripheral.delegate = self
peripheral.discoverServices(nil) // 发现所有服务
}
}
// 5. 外设服务交互
extension BluetoothManager: CBPeripheralDelegate {
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
guard let services = peripheral.services else { return }
for service in services {
// 发现特定服务的特征值
if service.uuid == CBUUID(string: "FFE0") {
peripheral.discoverCharacteristics(nil, for: service)
}
}
}
// 6. 获取特征值
func peripheral(_ peripheral: CBPeripheral,
didDiscoverCharacteristicsFor service: CBService,
error: Error?) {
guard let characteristics = service.characteristics else { return }
for char in characteristics {
// 订阅通知特征
if char.properties.contains(.notify) {
peripheral.setNotifyValue(true, for: char)
}
// 写入特征
if char.uuid == CBUUID(string: "FFE1") {
let data = Data([0x01, 0xA0])
peripheral.writeValue(data, for: char, type: .withResponse)
}
}
}
// 7. 处理数据接收
func peripheral(_ peripheral: CBPeripheral,
didUpdateValueFor characteristic: CBCharacteristic,
error: Error?) {
guard let data = characteristic.value else { return }
processReceivedData(data) // 自定义数据处理方法
}
}
关键问题解决方案
-
后台持续运行
在Capabilities中开启Background Modes并勾选Bluetooth LE accessories// 后台扫描配置 centralManager.scanForPeripherals(withServices: nil, options: [CBCentralManagerScanOptionAllowDuplicatesKey: true]) -
大数据分包处理
实现分包重组协议:
var receivedData = Data() func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic) { guard let chunk = characteristic.value else { return } // 协议设计:首字节0x01表示起始包,0x02中间包,0x03结束包 switch chunk.first { case 0x01: receivedData = chunk.dropFirst() case 0x02: receivedData.append(chunk.dropFirst()) case 0x03: receivedData.append(chunk.dropFirst()) handleCompletePacket(receivedData) default: break } } -
连接稳定性优化
// 断连自动重连 func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) { central.connect(peripheral, options: nil) }
// 设置连接参数
let options: [String: Any] = [
CBConnectPeripheralOptionNotifyOnConnectionKey: true,
CBConnectPeripheralOptionNotifyOnDisconnectionKey: true,
CBConnectPeripheralOptionNotifyOnNotificationKey: true
]
centralManager.connect(peripheral, options: options)
四、外设模式实现要点
```swift
// 1. 创建虚拟外设
let peripheralManager = CBPeripheralManager(delegate: self, queue: nil)
// 2. 创建服务特征
let characteristic = CBMutableCharacteristic(
type: CBUUID(string: "FFE1"),
properties: [.read, .write, .notify],
value: nil,
permissions: [.readable, .writeable]
)
let service = CBMutableService(type: CBUUID(string: "180D"), primary: true)
service.characteristics = [characteristic]
// 3. 广播服务
func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) {
if peripheral.state == .poweredOn {
peripheral.add(service)
peripheral.startAdvertising([
CBAdvertisementDataServiceUUIDsKey: [service.uuid],
CBAdvertisementDataLocalNameKey: "MyBLE_Device"
])
}
}
// 4. 处理中央设备请求
func peripheralManager(_ peripheral: CBPeripheralManager,
didReceiveRead request: CBATTRequest) {
if request.characteristic.uuid == CBUUID(string: "FFE1") {
request.value = "Ready".data(using: .utf8)
peripheral.respond(to: request, withResult: .success)
}
}
最佳实践与避坑指南
-
设备筛选策略
使用advertisementData精准识别:func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) { // 通过厂商数据过滤 if let manuData = advertisementData[CBAdvertisementDataManufacturerDataKey] as? Data { let companyID = manuData[0...1] if companyID == Data([0x4C, 0x00]) { // Apple设备标识 // 特殊处理 } } } -
能耗控制

// 连接后立即停止扫描 centralManager.stopScan()
// 按需设置通知间隔
peripheral.setNotifyValue(true, for: char,
enabled: true,
for: .default) // iOS 15+ 新增节电参数
3. 跨版本兼容
```swift
#if os(iOS) && !targetEnvironment(macCatalyst)
if #available(iOS 13.0, ) {
// 使用新的错误类型CBError
} else {
// 旧版错误处理
}
#endif
调试工具推荐
- 使用Apple官方
Bluetooth Explorer检测信号强度 LightBlue应用验证服务特征值结构PacketLogger.app抓取HCI层数据包
互动讨论: 您在BLE开发中遇到最难解决的连接问题是什么?是后台重连失败?数据丢包?还是设备兼容性问题?欢迎分享具体案例,我将提供针对性优化方案!
原创文章,作者:世雄 - 原生数据库架构专家,如若转载,请注明出处:https://idctop.com/article/25221.html