iOS 蓝牙 CoreBluetooth

1.建立中心角色

#import

CBCentralManager *manager;                                                                   manager = [[CBCentralManager alloc] initWithDelegate:selfqueue:nil];

2.判断手机蓝牙状态

//当手机的蓝牙状态发生改变时,调用该方法

-(void)centralManagerDidUpdateState:(CBCentralManager*)central{              if(central.state==CBCentralManagerStatePoweredOn){                                      //当蓝牙状态为开时 扫描外设                                                             [self.manager scanForPeripheralsWithServices:nil options:nil];                                 }                                                                                                                         }

3.当扫描到外设调用方法

-(void)centralManager:(CBCentralManager*)central didDiscoverPeripheral:(CBPeripheral*)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber*)RSSI

{

//连接外设   

[self.manager connectPeripheral:peripheral options:nil];

}

4.连接成功时调用方法

-(void)centralManager:(CBCentralManager*)central didConnectPeripheral:(CBPeripheral*)peripheral

{//停止扫描

[self.manager stopScan];

//设置外设的代理回调

peripheral.delegate=self;

//按照指定的UUID查找外设中的对应服务

[self.peripheraldiscoverServices:@[[CBUUIDUUIDWithString:@"蓝牙外设服务UUID"]]];

}

5找到相关服务时 调用方法

-(void)peripheral:(CBPeripheral*)peripheral didDiscoverServices:(NSError*)error

{

for(CBService*serviceinperipheral.services)

{

//在外设中所有的服务中找到准备查询的服务

if([service.UUIDisEqual:[CBUUIDUUIDWithString:@"蓝牙外设服务UUID"]]) {

//获得服务中的特征

[peripheraldiscoverCharacteristics:@[[CBUUIDUUIDWithString:@"蓝牙外设服务特征UUID"]]forService:service];

}

}

}

//当找到相关服务时,调用该方法

-(void)peripheral:(CBPeripheral*)peripheral didDiscoverServices:(NSError*)error

{

for(CBService*serviceinperipheral.services)

{

//在外设中所有的服务中找到准备查询的服务

if([service.UUIDisEqual:[CBUUIDUUIDWithString:@"服务UUID"]]) {

//获得服务中的特征

[peripheraldiscoverCharacteristics:@[[CBUUIDUUIDWithString:@"特征UUID"]]forService:service];

}

}

}

//获得特征里边的数据

-(void)peripheral:(CBPeripheral*)peripheral didUpdateValueForCharacteristic:(CBCharacteristic*)characteristic error:(NSError*)error

{  NSLog(@"%@",characteristic.value);  }

-(void)peripheral:(CBPeripheral*)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic*)characteristic error:(NSError*)error

{

if(characteristic.isNotifying) {

NSLog(@"%@",characteristic);

}

else

{

//断开与外设的连接

[self.managercancelPeripheralConnection:peripheral];

}

}

你可能感兴趣的:(iOS 蓝牙 CoreBluetooth)