- 最近做了几个蓝牙项目,写一下过程,方便大家.
本文章介绍手机为中央设备的情形
第一步 遵循代理
@interface DBBLEManager ()<CBCentralManagerDelegate,CBPeripheralDelegate>
第二步 设置蓝牙属性
@property (nonatomic ,strong)CBCentralManager *myCentralManager;
第三步 实例化
_myCentralManager = [[CBCentralManager alloc]initWithDelegate:self queue:nil options:nil];
第四步 实现代理方法
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
if (central.state == CBCentralManagerStatePoweredOn) {
NSLog(@"蓝牙已打开");
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], CBCentralManagerScanOptionAllowDuplicatesKey, nil];
扫描
[_myCentralManager scanForPeripheralsWithServices:nil options:options];
}else {
NSLog(@"蓝牙已关闭");
NSURL *url=[NSURL URLWithString:@"prefs:root=Bluetooth"];
[[UIApplication sharedApplication]openURL:url];
[DBTIPview ProgressHUD:@"设置-蓝牙-打开蓝牙"];
}
}
第五步 代理返回蓝牙外设 连接
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
{
[_myCentralManager connectPeripheral:peripheral options:nil];
}
第六步
连接上蓝牙
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
[_myCentralManager stopScan];
}
//连接失败
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(nullable NSError *)error{
}
//失去连接
-(void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error{
}
接下来会开放一个 蓝牙的简单封装