您的位置:首页 > 移动开发 > IOS开发

iOS 蓝牙连接的流程

2017-08-30 10:08 281 查看
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:(CBPeri
4000
pheral *)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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: