下面是两台iPhone6连接同一台蓝牙设备的结果:
**成功连接**** peripheral: with UUID: <__NSConcreteUUID 0x17003d980> 50084F69-BA5A-34AC-8A6E-6F0CEADB21CD**
****
****
**成功连接**** peripheral: with UUID: <__NSConcreteUUID 0x174036c00> 55B7D759-0F1E-6271-EA14-BC5A9C9EEEEC**
iOS的蓝牙开发很简单,只要包含一个库,创建CBCentralManager实例,实现代理方法,然后就可以直接和设备进行通信。
#define TRANSFER_SERVICE_UUID @"0000fff0-0000-1000-8000-00206f9c56cad"
#define TRANSFER_CHARACTERISTIC_UUID @"0000fff7-0000-1000-8000-00806f9c56cad"
2.在.h文件中导入两个头文件,并在接口中实现两个协议
#import"ViewController.h"
#import
//需要实现协议
@interfaceViewController () <CBCentralManagerDelegate,CBPeripheralDelegate>{}
#pragma mark 蓝牙设备
@property (strong,nonatomic)CBCentralManager *centralManager; //接收
@property (strong,nonatomic)CBPeripheral *discoveredPeripheral; //外设
@end
4.开始蓝牙配置#pragma mark 在初始化界面结束后设置自己为代理
@implementation ViewController
- (void)viewDidLoad {
[superviewDidLoad];
_centralManager = [[CBCentralManageralloc]initWithDelegate:selfqueue:nil];
}
#pragma mark 此处监控一下central的状态值,可以判断蓝牙是否开启/可用
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
NSMutableString *stringForCentralManagerState = [NSMutableStringstringWithString:@"UpdateState:"];
switch (central.state) {
caseCBCentralManagerStateUnknown:
[stringForCentralManagerStateappendString:@"Unkown\n"];
break;
caseCBCentralManagerStateUnsupported:
[stringForCentralManagerStateappendString:@"Unsupported\n"];
caseCBCentralManagerStateUnauthorized:
[stringForCentralManagerStateappendString:@"Unauthorized\n"];
caseCBCentralManagerStateResetting:
[stringForCentralManagerStateappendString:@"Resetting\n"];
caseCBCentralManagerStatePoweredOff:
[stringForCentralManagerStateappendString:@"PowerOff\n"];
caseCBCentralManagerStatePoweredOn:
//设备支持BLE并且可用
[stringForCentralManagerStateappendString:@"PoweredOn\n"];
//开始搜索
[selfscan];
break;
default:
[stringForCentralManagerStateappendString:@"none\n"];
break;
}
NSLog(@"%@", stringForCentralManagerState);
}
#pragma mark 扫描
- (void)scan
{ [self.centralManage scanForPeripheralsWithServices:@[[CBUUI UUIDWithString:TRANSFER_SERVICE_UUID]]
options:@{CBCentralManagerScanOptionAllowDuplicatesKey :@YES}];
NSLog(@"Scanning started");
}
#pragma mark 发现设备,连接
//一旦符合要求的设备被发现,就会回调此方法
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
{
NSLog(@"Discovered %@ at %@", peripheral.name, RSSI);
if (self.discoveredPeripheral != peripheral) {
self.discoveredPeripheral = peripheral;
// 连接
[self.centralManagerconnectPeripheral:peripheraloptions:nil];
NSLog(@"Connecting to peripheral %@", peripheral);
}
}
#pragma mark 未能连接的处理方法
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
NSLog(@"Failed to connect to %@. (%@)", peripheral, [errorlocalizedDescription]);
}
#pragma mark 当连接上设备
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
NSLog(@"Peripheral Connected");
//已连接上设备,故停止搜索
[self.centralManagerstopScan];
NSLog(@"Scanning stopped");
peripheral.delegate =self;
//寻找指定UUID的Service
[peripheraldiscoverServices:@[[CBUUIDUUIDWithString:TRANSFER_SERVICE_UUID]]];
}
#pragma mark 发现设备上指定Service会回调此处
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
{
if (error) {
NSLog(@"Error discovering services: %@", [errorlocalizedDescription]);
return;
}
//寻找指定UUID的Characteristic
for (CBService *servicein peripheral.services) {
[peripheraldiscoverCharacteristics:@[[CBUUIDUUIDWithString:TRANSFER_CHARACTERISTIC_UUID]]
forService:service];
}
}
#pragma mark 找到指定UUID的Characteristic会回调此处
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{
if (error) {
NSLog(@"Error discovering characteristics: %@", [errorlocalizedDescription]);
return;
}
for (CBCharacteristic *characteristicin service.characteristics) {
if ([characteristic.UUIDisEqual:[CBUUIDUUIDWithString:TRANSFER_CHARACTERISTIC_UUID]]) {
NSLog(@"find the characteristic");
[peripheralsetNotifyValue:YESforCharacteristic:characteristic];
}
}
}
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
if (error) {
NSLog(@"Error discovering characteristics: %@", [errorlocalizedDescription]);
return;
}
NSLog(@"value --> %@",characteristic.value);
#pragma mark 把接收到的数据进行截取
//此处我们就可以拿到value值对其进行数据解析了
NSData *data = characteristic.value;
}
#pragma mark 蓝牙断开后自动重连
-(void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
NSLog(@"Peripheral Disconnected");
self.discoveredPeripheral =nil;
// 重新开启搜索
[selfscan];
UIAlertView *alert = [[UIAlertViewalloc]initWithTitle:@"蓝牙连接状态"message:@"连接已断开"delegate:nilcancelButtonTitle:@"确定"otherButtonTitles:@"关闭",nil];
[alert show];
}
5.蓝牙后台运行