iOS 藍牙連接的流程:
一、在 .h 文件中
1、加入頭文件 #import <CoreBluetooth/CoreBluetooth.h>
2、聲明以下變量
@property (nonatomic, strong) CBCentralManager *m_manger; //管理者
@property (nonatomic, strong) CBService *m_service; //服務
@property (nonatomic, strong) CBPeripheral *m_peripheral; //外設
1、初始化管理者,掃描外設,連接指定外設
_m_manger = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
[_m_manger scanForPeripheralsWithServices:nil options:nil];
[self.m_manger connectPeripheral:peripheral options:description];
2、判斷系統藍牙是否開啓
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
3、實現發現外設的回調
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI
4、實現已連接外設的回調
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral{
_m_peripheral = peripheral;
_m_peripheral.delegate = self;
[_m_peripheral discoverServices:nil];
}
5、實現發現服務的回調
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{
for (CBService *service in peripheral.services) {
[peripheral discoverCharacteristics:nil forService:service];
}
}
6、實現發現特徵值的回調,並監聽特徵值
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error{
if ([service.UUID isEqual:[UUIDTool serviceUUID01]]) {
for (CBCharacteristic *characteristic in service.characteristics) {
if ([characteristic.UUID isEqual:[UUIDTool characteristic01UUID]]) {
}
// 監聽特徵值
[_m_peripheral setNotifyValue:YES forCharacteristic:characteristic];
}
}
}
7、實現特徵值改變的回調
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
8、實現發送指令反饋信息的回調
- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
if (!error) {
NSLog(@"發送指令成功");
}
else{
NSLog(@"發送指令失敗");
}
}
9、實現外設連接失敗的回調
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
10、實現外設連接後,再失去連接的回調
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error