1 首先我带入了BLE包,实现蓝牙协议
2 扫描周围的蓝牙设备
self.beaconFinder = [KRBeaconFinder sharedFinder];
__weak typeof(self) weakSelf = self;
[_beaconFinder setBleScanningEnumerator:^(CBPeripheral *peripheral, NSDictionary *advertisements, NSNumber *RSSI)
{
// NSLog(@"The advertisement with identifer: %@, state: %d, name: %@, services: %@, description: %@",
// [peripheral identifier],
// [peripheral state],
// [peripheral name],
// [peripheral services],
// [advertisements description]);
//过滤(hasPrefix)
if ([peripheral.name hasPrefix:@"XY"]) {
if (![weakSelf.detectedBeacons containsObject:peripheral]) {
[weakSelf.detectedBeacons addObject:peripheral];
[weakSelf.beaconTableview reloadData];
}
}
}];
//启动
[_beaconFinder bleScan];
3 连接蓝牙设备
[[KRBeaconCentralManager sharedManager].centralManager connectPeripheral:beacon options:[NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:CBConnectPeripheralOptionNotifyOnDisconnectionKey]];
3.1 连接设备成功后会回调一个方法
-(void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
//...
}
4 外设设置代理以便以后数据交流
peripheral.delegate = self;
5 查询蓝牙服务
[peripheral discoverServices:nil];
5.1蓝牙服务通知通过的回调
-(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
{
}
6 查询服务所带的特征值
[peripheral discoverCharacteristics:nil forService:service];
6.1返回的蓝牙特征值通知通过代理实现的回调方法
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{
}
7 给蓝牙发送数据
[peripheral readValueForCharacteristic:service.characteristics[0]]
7.1 给蓝牙发送数据成功的代理回调方法
- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
}
8 处理蓝牙发过来得数据的回调方法
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
[ peripheral writeValue:tempData forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];
}
个人敲了一下测试过的,希望有大神帮忙指点一下。。。。。。。。。。。。。。。。