1,导入
2,#import <CoreBluetooth/CoreBluetooth.h>
3,协议<CBCentralManagerDelegate,CBPeripheralDelegate>
4,CBCentralManager *cm = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
cm.delegate = self;
//scan外设
NSDictionary* scanOptions = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:CBCentralManagerScanOptionAllowDuplicatesKey];
[cm scanForPeripheralsWithServices:nil options:scanOptions];
- (void) centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI//scan到设备就会调用此方法
//connect设备
NSDictionary* scanOptions = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:CBCentralManagerScanOptionAllowDuplicatesKey];
[cm connectPeripheral:(CBPeripheral *)[_peripheralArray objectAtIndex:indexPath.row] options:scanOptions];
- (void) centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error//连接外设时调用
- (void) centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral//当连接上一个外设 CBCentralManager 代理 处理此方法
4,//查询设备服务特征,注意 这块的peripheral 一定得为连接上的设备 后续发送接收数据有用
[peripheral setDelegate:self];
[peripheral discoverServices:nil];
#pragma mark -- CBPeripheralDelegate
//返回的蓝牙服务通知通过代理实现[_peripheral discoverServices:nil];
- (void) peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
//查询服务所带的特征值[_peripheral discoverCharacteristics:nil forService:myService];
- (void) peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
5,
//发送数据
[peripheral writeValue:datastr forCharacteristic:writeCharacteristic type:CBCharacteristicWriteWithResponse];
//发送成功调用
- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
//处理蓝牙发过来的数据
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error