在 iOS 应用开发中,蓝牙开发是一个重点, 是 iOS 开发人员必须掌握的一个知识。今天小编就将为大家分享一篇 iOS 大牛写的有关蓝牙开发中,使用 app 发布一个 peripheral,给其他的 central 连接的实现方法。
peripheral 模式的流程
-
打开 peripheralManager,设置 peripheralManager 的委托
-
创建 characteristics,characteristics 的 description 创建 service,把 characteristics 添加到 service 中,再把 service 添加到 peripheralManager 中
-
开启广播 advertising
-
对 central 的操作进行响应
-
4.1 读 characteristics 请求
-
4.2 写 characteristics 请求
-
4.4 订阅和取消订阅 characteristics
-
准备开发环境
1 、Xcode
2、 开发证书和手机(蓝牙程序需要使用使用真机调试,使用模拟器也可以调试,但是方法很负责,本篇分享不做过多赘述),如果不行可以使用 osx 程序调试
3、 蓝牙外设
实现步骤
-
打开 peripheralManager,设置 peripheralManager 的委托。设置当前 ViewController 实现 CBPeripheralManagerDelegate 委托
@interface BePeripheralViewController : UIViewController
初始化 peripheralManager
/*
和CBCentralManager类似,蓝牙设备打开需要一定时间,打开成功后会进入委托方法
- (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral;
模拟器永远也不会得CBPeripheralManagerStatePoweredOn状态
*/
peripheralManager = [[CBPeripheralManager alloc]initWithDelegate:self queue:nil];
- 创建 characteristics,characteristics 的 description ,创建 service,把 characteristics 添加到 service 中,再把 service 添加到 peripheralManager 中
在委托方法 - (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral 中,当 peripheral 成功打开后,才可以配置 service 和 characteristics。 这里创建的 service 和 chara 对象是 CBMutableCharacteristic 和 CBMutableService。他们的区别就像 NSArray 和 NSMutableArray 区别类似。 我们先创建 characteristics 和 description,description 是 characteristics 的描述,描述分很多种, 这里不细说了,常用的就是 CBUUIDCharacteristicUserDescriptionString。
//peripheralManager 状态改变
-
(void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral{
switch (peripheral.state) {
//在这里判断蓝牙设别的状态 当开启了则可调用 setUp方法(自定义) case CBPeripheralManagerStatePoweredOn: NSLog(@"powered on"); [info setText:[NSString stringWithFormat:@"设备名%@已经打开,可以使用center进行连接",LocalNameKey]]; [self setUp]; break; case CBPeripheralManagerStatePoweredOff: NSLog(@"powered off"); [info setText:@"powered off"]; break; default: break;
}
}
//配置 bluetooch 的
-(void)setUp{
//characteristics 字段描述
CBUUID *CBUUIDCharacteristicUserDescriptionStringUUID = [CBUUID UUIDWithString:CBUUIDCharacteristicUserDescriptionString];
/*
可以通知的Characteristic
properties:CBCharacteristicPropertyNotify
permissions CBAttributePermissionsReadable
*/
CBMutableCharacteristic *notiyCharacteristic = [[CBMutableCharacteristic alloc]initWithType:[CBUUID UUIDWithString:notiyCharacteristicUUID] properties:CBCharacteristicPropertyNotify value:nil permissions:CBAttributePermissionsReadable];
/*
可读写的characteristics
properties:CBCharacteristicPropertyWrite | CBCharacteristicPropertyRead
permissions CBAttributePermissionsReadable | CBAttributePermissionsWriteable
*/
CBMutableCharacteristic *readwriteCharacteristic = [[CBMutableCharacteristic alloc]initWithType:[CBUUID UUIDWithString:readwriteCharacteristicUUID] properties:CBCharacteristicPropertyWrite | CBCharacteristicPropertyRead value:nil permissions:CBAttributePermissionsReadable | CBAttributePermissionsWriteable];
//设置description
CBMutableDescriptor *readwriteCharacteristicDescription1 = [[CBMutableDescriptor alloc]initWithType: CBUUIDCharacteristicUserDescriptionStringUUID value:@"name"];
[readwriteCharacteristic setDescriptors:@[readwriteCharacteristicDescription1]];
/*
只读的Characteristic
properties:CBCharacteristicPropertyRead
permissions CBAttributePermissionsReadable
*/
CBMutableCharacteristic *readCharacteristic = [[CBMutableCharacteristic alloc]initWithType:[CBUUID UUIDWithString:readCharacteristicUUID] properties:CBCharacteristicPropertyRead value:nil permissions:CBAttributePermissionsReadable];
//service1初始化并加入两个characteristics
CBMutableService *service1 = [[CBMutableService alloc]initWithType:[CBUUID UUIDWithString:ServiceUUID1] primary:YES];
[service1 setCharacteristics:@[notiyCharacteristic,readwriteCharacteristic]];
//service2初始化并加入一个characteristics
CBMutableService *service2 = [[CBMutableService alloc]initWithType:[CBUUID UUIDWithString:ServiceUUID2] primary:YES];
[service2 setCharacteristics:@[readCharacteristic]];
//添加后就会调用代理的- (void)peripheralManager:(CBPeripheralManager *)peripheral didAddService:(CBService *)service error:(NSError *)error
[peripheralManager addService:service1];
[peripheralManager addService:service2];
}
- 开启广播 advertising
//perihpheral 添加了 service
-
(void)peripheralManager:(CBPeripheralManager *)peripheral didAddService:(CBService *)service error:(NSError *)error{
if (error == nil) {
serviceNum++;
}
//因为我们添加了 2 个服务,所以想两次都添加完成后才去发送广播
if (serviceNum==2) {
//添加服务后可以在此向外界发出通告 调用完这个方法后会调用代理的 //(void)peripheralManagerDidStartAdvertising:(CBPeripheralManager *)peripheral error:(NSError *)error [peripheralManager startAdvertising:@{ CBAdvertisementDataServiceUUIDsKey : @[[CBUUID UUIDWithString:ServiceUUID1],[CBUUID UUIDWithString:ServiceUUID2]], CBAdvertisementDataLocalNameKey : LocalNameKey } ];
}
}
//peripheral 开始发送 advertising
-
(void)peripheralManagerDidStartAdvertising:(CBPeripheralManager *)peripheral error:(NSError *)error{
NSLog(@"in peripheralManagerDidStartAdvertisiong");
}
- 对 central 的操作进行响应
-
4.1 读 characteristics 请求
-
4.2 写 characteristics 请求
-
4.3 订阅和取消订阅 characteristics
//订阅 characteristics
-(void)peripheralManager:(CBPeripheralManager *)peripheral central:(CBCentral *)central didSubscribeToCharacteristic:(CBCharacteristic *)characteristic{
NSLog(@"订阅了 %@的数据",characteristic.UUID);
//每秒执行一次给主设备发送一个当前时间的秒数
timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(sendData:) userInfo:characteristic repeats:YES];
}
//取消订阅 characteristics
-(void)peripheralManager:(CBPeripheralManager *)peripheral central:(CBCentral *)central didUnsubscribeFromCharacteristic:(CBCharacteristic *)characteristic{
NSLog(@"取消订阅 %@的数据",characteristic.UUID);
//取消回应
[timer invalidate];
}
//发送数据,发送当前时间的秒数
-(BOOL)sendData:(NSTimer *)t {
CBMutableCharacteristic *characteristic = t.userInfo;
NSDateFormatter *dft = [[NSDateFormatter alloc]init];
[dft setDateFormat:@"ss"];
NSLog(@"%@",[dft stringFromDate:[NSDate date]]);
//执行回应Central通知数据
return [peripheralManager updateValue:[[dft stringFromDate:[NSDate date]] dataUsingEncoding:NSUTF8StringEncoding] forCharacteristic:(CBMutableCharacteristic *)characteristic
onSubscribedCentrals:nil];
}
//读 characteristics 请求
-
(void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveReadRequest:(CBATTRequest *)request{
NSLog(@"didReceiveReadRequest");
//判断是否有读数据的权限
if (request.characteristic.properties & CBCharacteristicPropertyRead) {
NSData *data = request.characteristic.value; [request setValue:data]; //对请求作出成功响应 [peripheralManager respondToRequest:request withResult:CBATTErrorSuccess];
}else{
[peripheralManager respondToRequest:request withResult:CBATTErrorWriteNotPermitted];
}
}
//写 characteristics 请求
-
(void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveWriteRequests:(NSArray *)requests{
NSLog(@"didReceiveWriteRequests");
CBATTRequest *request = requests[0];
//判断是否有写数据的权限
if (request.characteristic.properties & CBCharacteristicPropertyWrite) {
//需要转换成CBMutableCharacteristic对象才能进行写值 CBMutableCharacteristic *c =(CBMutableCharacteristic *)request.characteristic; c.value = request.value; [peripheralManager respondToRequest:request withResult:CBATTErrorSuccess];
}else{
[peripheralManager respondToRequest:request withResult:CBATTErrorWriteNotPermitted];
}
}
以上就是 iOS 蓝牙开发中,app 作为外设被连接的具体实现方法,希望对大家开发这项功能有所帮助吧。
相关文章:《DASH 中查询 iOS 文档的方法》 http://www.maiziedu.com/group/article/5618/
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于