最近一段时间一直在做公司的BLE蓝牙SDK,sdk主要负责外设和手机的连接以及数据通信。过程中遇到了一些比较有价值的问题,现在总结记录下。
蓝牙开发使用系统框架
#import <CoreBluetooth/CoreBluetooth.h>
使用[[CBCentralManager alloc] initWithDelegate:self queue:nil]
初始化CBCentralManager
对象。(设置CBCentralManagerDelegate
为self,nil表示在主线程) 初始化成功后系统会自动检测蓝牙状态。实现centralManagerDidUpdateState:
代理方法可实时获取蓝牙状态。当central.state
为CBManagerStatePoweredOn
时表示可用。
初始化完成可使用
[self.centralManager scanForPeripheralsWithServices:nil options:nil]
方法扫描周围设备(Services表示只扫描具有某些ServiceUUID的设备,nil为扫描全部)。 当扫描到设备时会执行代理方法centralManager:didDiscoverPeripheral:advertisementData:RSSI:
返回每一个扫描到的设备及设备的相关信息。
为了使用方便,可以把扫描的设备、连接的设备、设备的服务、设备的特征分别保存到数组中
@property(nonatomic, strong) NSMutableArray<CBPeripheral *> *peripheralArr; //扫描到的设备数组
@property(nonatomic, strong) NSMutableArray<CBPeripheral *> *currentPeripheralArr; //当前连接的所有设备
@property(nonatomic, strong) NSMutableArray<CBService *> *serviceArr; //当前连接设备的服务
@property(nonatomic, strong) NSMutableArray<CBCharacteristic *> *characteristicArr; //当前连接的设备的所有特征
复制代码
保存到数组中的设备可通过
UUID
来进行区分。从iOS7
之后苹果不提供外设的mac</