iOS蓝牙开发总结
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)有可能会导致蓝牙数据发送失败,无法操控蓝牙设备。