1.初始化
-(instancetype)initWithDelegate:(nullable id<CBCentralManagerDelegate>)delegate
queue:(nullable dispatch_queue_t)queue
options:(nullable NSDictionary<NSString *, id> *)options NS_AVAILABLE(10_9, 7_0) NS_DESIGNATED_INITIALIZER;
options有以下兩種:
CBCentralManagerOptionShowPowerAlertKey 藍牙沒打開時會顯示一個提示框
CBCentralManagerOptionRestoreIdentifierKey CBCentralManager恢復(fù)的IdentifierKey
2.掃描
-(void)scanForPeripheralsWithServices:(nullable NSArray<CBUUID *> *)serviceUUIDs options:(nullable NSDictionary<NSString *, id> *)options;
第一個參數(shù)是UUID:
外設(shè)廣播UUID時, 可以在這里填寫特定UUID,用于搜索特定UUID的外設(shè).
第二個參數(shù):
CBCentralManagerScanOptionAllowDuplicatesKey
key值是NSNumber,默認值為NO表示不會重復(fù)掃描已經(jīng)發(fā)現(xiàn)的設(shè)備,如需要不斷獲取最新的信號強度RSSI所以一般設(shè)為YES了
CBCentralManagerScanOptionSolicitedServiceUUIDsKey
你想掃描的serviceUUID數(shù)組
-(void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *, id> *)advertisementData RSSI:(NSNumber *)RSSI;
在這個代理方法里獲取掃描到的數(shù)據(jù),外設(shè),廣播數(shù)據(jù),信號強度
3.連接
-(void)connectPeripheral:(CBPeripheral *)peripheral options:(nullable NSDictionary<NSString *, id> *)options;
第一個參數(shù):你想要連接的外設(shè)
第二個參數(shù):
CBConnectPeripheralOptionNotifyOnConnectionKey 在程序被掛起時,連接成功顯示Alert提醒框
CBConnectPeripheralOptionNotifyOnDisconnectionKey 在程序被掛起時,斷開連接顯示Alert提醒框
CBConnectPeripheralOptionNotifyOnNotificationKey 在程序被掛起時,顯示所有的提醒消息
其他三個感覺用不到,就不一一列舉了.
在連接成功后,需要調(diào)用- (void)discoverServices:(nullable NSArray<CBUUID *> *)serviceUUIDs; 去發(fā)現(xiàn)外設(shè)的服務(wù)
4.服務(wù)
-(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(nullable NSError *)error 發(fā)現(xiàn)服務(wù)的回調(diào)方法
發(fā)現(xiàn)服務(wù)后, 需要調(diào)用- (void)discoverCharacteristics:(nullable NSArray<CBUUID *> *)characteristicUUIDs forService:(CBService *)service; 去獲取外設(shè)特征.
5.特征
-(void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(nullable NSError *)error; 獲取外設(shè)特征回調(diào)
1.可以在這個回調(diào)里獲取到自己需要的特征值, 讀,寫等.
2.可以在這個回調(diào)里訂閱讀,被動獲取外設(shè)發(fā)過來的數(shù)據(jù).
3.可以在這個回調(diào)里判斷特征值權(quán)限,使用- (void)readValueForCharacteristic:(CBCharacteristic *)characteristic;這個方法, 如果不允許讀, 那就需要配對連接之后才能讀,可以以此來判斷是否需要配對, 以及什么時候配對完成, 因為蘋果系統(tǒng)API并未提供任何有關(guān)配對狀態(tài)的屬性或方法.
6.讀寫
-(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(nullable NSError *)error; 這是讀的回調(diào)方法.
-(void)writeValue:(NSData *)data forCharacteristic:(CBCharacteristic *)characteristic type:(CBCharacteristicWriteType)type; 這是寫的方法.
7.藍牙連接的流程圖

最近一直在研究BLE藍牙, 歡迎大家一起交流分享.
推薦一個牛批的藍牙庫babyBluetooth.