iOS蓝牙4.0开发(二)iOS设备之间的通讯

上一节通过与外设之间文件传输讲解了中心角色(central),这一节通过iOS设备间的数据传输来详细讲解外设角色(peripheral)

实现细节

首先在我自己类的头文件中要包含CoreBluetooth的头文件,并继承协议CBPeripheralManagerDelegate

1.创建我们的外设角色

_peripheralManager = [[CBPeripheralManager alloc] initWithDelegate:self queue:nil];和CBCentralManager一样,CBPeripheralManager将CBCentralManagerDelegate协议委托给当前类实例,这里有个@required协议方法

– (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral;

你必须实现这个方法来确认外设的状态是可用的时候对它发布命令,当外设角色的状态发生变化的时候会触发这个方法。你只能在peripheral的state是CBPeripheralManagerStatePoweredOn的时候对它发布命令,当status的值低于CBPeripheralManagerStatePoweredOn的时候意味着广播停止,并且任何已连接的中心都已经断开,当status的值低于CBPeripheralManagerStatePoweredOff时,广播已经停止,而且必须重新发出广播。2.创建服务

self.transferCharacteristic = [[CBMutableCharacteristic alloc] initWithType:[CBUUID UUIDWithString:TRANSFER_CHARACTERISTIC_UUID]properties:CBCharacteristicPropertyNotifyvalue:nilpermissions:CBAttributePermissionsReadable];CBMutableService *transferService = [[CBMutableService alloc] initWithType:[CBUUID UUIDWithString:TRANSFER_SERVICE_UUID]primary:YES];transferService.characteristics = @[self.transferCharacteristic];[self.peripheralManager addService:transferService];上面总共4行代码;第一行代码创建特征,并设置特征uuid,属性(可读,可写,可监听等,上一节已经讲过),值(为nil表示是动态值,生命周期内会发生变化),对值的操作权限,这里是可读,如果需要接受接受中心角色的数据请求的话,就要设置相应地特征权限为CBAttributePermissionsWriteable,这样中心角色才能对该特征值就行写操作;第二行代码创建服务;第三行代码设置服务的特征,这里只有一个,我们也可以设置多个;第四行将服务添加到我们的外设中。addService:会触发以下代理方法- (void)peripheralManager:(CBPeripheralManager *)peripheral didAddService:(CBService *)service error:(NSError *)error

如果error为nil,则添加成功,这时,我们可以在这里广播服务了。否则失败。3.广播服务

[self.peripheralManager startAdvertising:@{CBAdvertisementDataLocalNameKey:@"ceshi.mp4", CBAdvertisementDataServiceUUIDsKey : @[[CBUUID UUIDWithString:TRANSFER_SERVICE_UUID]] }];

调用startAdvertising:方法以后会触发代理调用以下方法,,error为空,广播成功,否则失败。

– (void)peripheralManagerDidStartAdvertising:(CBPeripheralManager *)peripheral error:(NSError *)error

如果中央订阅了这个服务,会触发以下代理方法:

– (void)peripheralManager:(CBPeripheralManager *)peripheral central:(CBCentral *)central didSubscribeToCharacteristic:(CBCharacteristic *)characteristic;

这里的central就是我们收发数据的对象,也就是下面的self.central。4.发送数据

BOOL didSend = [self.peripheralManager updateValue:[NSData dataWithBytes:send_msg length:bytesRead] forCharacteristic:self.transferCharacteristic onSubscribedCentrals:[NSArray arrayWithObjects:self.central, nil]];如果以上方法因为发送队列已满而调用失败,当有可用的发送队列空间的时候会触发以下代理方法,因此可以在这里面对数据重新发送。- (void)peripheralManagerIsReadyToUpdateSubscribers:(CBPeripheralManager *)peripheral;

5.接收数据

通过以下代理方法接受数据

– (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveWriteRequests:(NSArray *)requests{// NSLog(@"didReceiveWriteRequests: %@", requests);for (CBATTRequest *request in requests) {NSString *aString = [[NSString alloc] initWithData:request.value encoding:NSASCIIStringEncoding];NSLog(@"Receive:%@",aString);}}

这里自己做了一个收发数据的小Demo,两个都可以收发数据,一个发送,另外一个就接受数据。

Demo地址

伟人之所以伟大,是因为他与别人共处逆境时,

iOS蓝牙4.0开发(二)iOS设备之间的通讯

相关文章:

你感兴趣的文章:

标签云: