我即将开始开发一个iOS应用程序,它依赖于能够通过蓝牙LE广告发送小块数据(因此iOS设备是外围设备)。
阅读以下苹果文档时,我无意中发现了以下内容:
也就是说,外围管理器对象只支持两个键: CBAdvertisementDataLocalNameKey和CBAdvertisementDataServiceUUIDsKey。
这是否意味着我无法具体说明所宣传的数据,并且基本上仅限于设备名称(常量)?
我给人的印象是,我可以随意为大约28字节的数据做广告。如果广告定制数据是不可能的,我不想开始一个重大项目。
发布于 2015-10-20 10:52:09
答案是-你可以!如果你进一步阅读文档,你就会知道如何去做。
阅读完这和这文档之后,我建议您逐行查看中央-外围组合这里的实现。
下面简要介绍一下如何做到这一点(通过外围触发器在中央对应的peripheral:didUpdateValueForCharacteristic:上编写数据):
- (void)peripheralManager:(CBPeripheralManager *)peripheral central:(CBCentral *)central didSubscribeToCharacteristic:(CBCharacteristic *)characteristic {
_dataToSend = [_textView.text dataUsingEncoding:NSUTF8StringEncoding];
_sendDataIndex = 0;
[self sendData];
}
- (void)sendData {
static BOOL sendingEOM = NO;
// end of message?
if (sendingEOM) {
BOOL didSend = [self.peripheralManager updateValue:[@"EOM" dataUsingEncoding:NSUTF8StringEncoding] forCharacteristic:self.transferCharacteristic onSubscribedCentrals:nil];
if (didSend) {
// It did, so mark it as sent
sendingEOM = NO;
}
// didn't send, so we'll exit and wait for peripheralManagerIsReadyToUpdateSubscribers to call sendData again
return;
}
// We're sending data
// Is there any left to send?
if (self.sendDataIndex >= self.dataToSend.length) {
// No data left. Do nothing
return;
}
// There's data left, so send until the callback fails, or we're done.
BOOL didSend = YES;
while (didSend) {
// Work out how big it should be
NSInteger amountToSend = self.dataToSend.length - self.sendDataIndex;
// Can't be longer than 20 bytes
if (amountToSend > NOTIFY_MTU) amountToSend = NOTIFY_MTU;
// Copy out the data we want
NSData *chunk = [NSData dataWithBytes:self.dataToSend.bytes+self.sendDataIndex length:amountToSend];
didSend = [self.peripheralManager updateValue:chunk forCharacteristic:self.transferCharacteristic onSubscribedCentrals:nil];
// If it didn't work, drop out and wait for the callback
if (!didSend) {
return;
}
NSString *stringFromData = [[NSString alloc] initWithData:chunk encoding:NSUTF8StringEncoding];
NSLog(@"Sent: %@", stringFromData);
// It did send, so update our index
self.sendDataIndex += amountToSend;
// Was it the last one?
if (self.sendDataIndex >= self.dataToSend.length) {
// Set this so if the send fails, we'll send it next time
sendingEOM = YES;
BOOL eomSent = [self.peripheralManager updateValue:[@"EOM" dataUsingEncoding:NSUTF8StringEncoding] forCharacteristic:self.transferCharacteristic onSubscribedCentrals:nil];
if (eomSent) {
// It sent, we're all done
sendingEOM = NO;
NSLog(@"Sent: EOM");
}
return;
}
}
}https://stackoverflow.com/questions/33234349
复制相似问题