Apple蓝牙框架CoreBluetooth
Apple蓝牙框架CoreBluetooth

Apple蓝牙框架CoreBluetooth

CoreBluetooth 是 Apple 提供的官方框架,用于在 iOS、macOS、watchOS 和 tvOS 上实现蓝牙低功耗(Bluetooth Low Energy, BLE)通信。

它支持开发蓝牙中心设备(Central)或外设(Peripheral),以便:

1、搜索并连接蓝牙设备。

2、读取/写入蓝牙特征值(Characteristic)。

3、实现 BLE 设备通信协议(如智能手环、蓝牙打印机、血压计等)。

CoreBluetooth角色

1、Central(中心):搜索 BLE 设备、连接设备、读取/写入数据。

2、Peripheral(外设):向外广播服务、接收中心请求、提供数据。

主要类

1、CBCentralManager:中心设备管理器(扫描/连接 BLE 设备)。

2、CBPeripheral:表示某个外设(扫描到或连接的设备)。

3、CBPeripheralManager:作为外设广播服务和特征(Peripheral 模式)。

4、CBService:设备的某个服务(可以包含多个特征)。

5、CBCharacteristic:特征值(数据点),可读、可写、可通知。

6、CBDescriptor:特征的附加描述(如说明、单位等)。

基本流程

1、创建 CBCentralManager 实例。

2、等待 centralManagerDidUpdateState 状态为 .poweredOn。

3、调用 scanForPeripherals(withServices:) 开始扫描设备。

4、连接目标设备(connect(_:options:))。

5、扫描服务(discoverServices),然后扫描特征(discoverCharacteristics)。

6、读取/写入特征或订阅通知(notify)。

使用示例

1、扫描并连接蓝牙设备(中心模式)

import CoreBluetooth

class BluetoothManager: NSObject, CBCentralManagerDelegate, CBPeripheralDelegate {
    var centralManager: CBCentralManager!
    var discoveredPeripheral: CBPeripheral?

    override init() {
        super.init()
        centralManager = CBCentralManager(delegate: self, queue: nil)
    }

    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        if central.state == .poweredOn {
            centralManager.scanForPeripherals(withServices: nil, options: nil)
            print("开始扫描蓝牙设备...")
        } else {
            print("蓝牙不可用")
        }
    }

    func centralManager(_ central: CBCentralManager, 
                        didDiscover peripheral: CBPeripheral, 
                        advertisementData: [String : Any], 
                        rssi RSSI: NSNumber) {
        print("发现设备:\(peripheral.name ?? "Unknown")")
        discoveredPeripheral = peripheral
        centralManager.stopScan()
        centralManager.connect(peripheral, options: nil)
    }

    func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
        print("已连接:\(peripheral.name ?? "Unknown")")
        peripheral.delegate = self
        peripheral.discoverServices(nil)
    }

    func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
        guard let services = peripheral.services else { return }
        for service in services {
            peripheral.discoverCharacteristics(nil, for: service)
        }
    }

    func peripheral(_ peripheral: CBPeripheral, 
                    didDiscoverCharacteristicsFor service: CBService, 
                    error: Error?) {
        guard let characteristics = service.characteristics else { return }
        for characteristic in characteristics {
            if characteristic.properties.contains(.read) {
                peripheral.readValue(for: characteristic)
            }
        }
    }

    func peripheral(_ peripheral: CBPeripheral, 
                    didUpdateValueFor characteristic: CBCharacteristic, 
                    error: Error?) {
        if let value = characteristic.value {
            print("读取到数据:\(value)")
        }
    }
}

注意事项

1、真机调试(模拟器不支持蓝牙)。

2、用户授权蓝牙访问(iOS 13+ 必须在 Info.plist 中添加权限):

<key>NSBluetoothAlwaysUsageDescription</key>
<string>我们需要使用蓝牙来连接设备</string>

应用场景

1、连接 BLE 设备(智能手环、健康设备)。

2、自定义蓝牙通信协议。

3、iOS/macOS 设备之间 BLE 通信(一个为 central,一个为 peripheral)。

4、开发蓝牙调试工具(比如 BLE Scanner)。

总结

CoreBluetooth为Apple官方框架,支持BLE 4.0+,委托(Delegate)驱动架构。

异步操作多,状态维护复杂,如果仅连接某类设备,可以使用MFi或第三方SDK(如打印机SDK)替代。

   

如果您认为这篇文章给您带来了帮助,您可以在此通过支付宝或者微信打赏网站开发者。

欢迎加入我们的 微信交流群QQ交流群,交流更多精彩内容!
微信交流群二维码 QQ交流群二维码

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注