iOS 蓝牙连接的流程

iOS 蓝牙连接的流程:

一、在 .h 文件中

1、加入头文件 #import 

2、声明以下变量

@property (nonatomic, strong)   CBCentralManager *m_manger; //管理者
@property (nonatomic, strong)   CBService        *m_service; //服务
@property (nonatomic, strong)   CBPeripheral     *m_peripheral;  //外设


二、在 .m 文件中

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 *)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

你可能感兴趣的:(蓝牙)