iOS 蓝牙连接的流程

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;  //外设


二、在 .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<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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值