1.创建蓝牙管理中心
@property(strong, nonatomic) CBCentralManager *activeCentralManager;
_activeCentralManager = [[CBCentralManager alloc] initWithDelegate:(id<CBCentralManagerDelegate>)self queue:dispatch_get_main_queue()];
2.扫描外围设备(scan)
NSDictionary *options = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:CBCentralManagerScanOptionAllowDuplicatesKey];
CBCentralManagerScanOptionAllowDuplicatesKey 的做用是:若是是同一设备会屡次扫描。
[_activeCentralManager scanForPeripheralsWithServices:nil options:options];
3.链接外设(connect)
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
{
if ([_activeCentralManager isEqual:central]) {
[self connect:peripheral];
}
}
- (void)connectDevice:(id)device{
if (![peripheral services]){
// 链接设备
// connectPeripheral方法链接成功后,会调用centralManager:didConnectPeripheral:
[_activeCentralManager connectPeripheral:peripheral options:nil];
}
else{
//链接失败
}
}
4.扫描外设中的服务和特征(discover)
-(void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral{
if ([_activeCentralManager isEqual:central]) {
if (peripheral != nil){
NSLog(@"链接成功");
// 若是当前设备是已链接设备开始扫描服务
NSArray *serviceArray = [self getServiceArray];
[peripheral setDelegate:(id<CBPeripheralDelegate>)self];
[peripheral discoverServices:serviceArray]; //执行完成此语句后 会执行discoverServices:的回调方法didDiscoverServices:
//serviceArray中能够包含指定的广播 好比:18F5
//[peripheral discoverServices:nil]; //当穿入nil时 默认扫描全部广播
}
}
}
5.与外设进行数据交互(进行特征值更新)
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
}//此方法能够获取到你想要的外设数据(存放在characteristic.value中)
if (characteristic != nil) {
[_activePeripheral writeValue:data forCharacteristic:characteristic type:CBCharacteristicWriteWithoutResponse];//写入数据
return YES;
}
此处需注意 发送数据时writeValue: forCharacteristic: type:中的type应设置为响应模式发送 (CBCharacteristicWriteWithResponse)若是设置为非响应的模式(CBCharacteristicWriteWithoutResponse)有可能会致使蓝牙数据发送失败,没法操控蓝牙设备。atom