我即将开始开发iOS应用程序,该应用程序依赖于能够通过蓝牙LE广告发送小块数据(因此iOS设备是外围设备)。
阅读以下Apple documentation我偶然发现了以下内容:
也就是说,外围设备管理器只支持两个密钥 对象:CBAdvertisementDataLocalNameKey和 CBAdvertisementDataServiceUUIDsKey。
这是否意味着我无法指定广告的数据,而且我本质上仅限于设备名称(常量)?
我的印象是我可以根据自己的判断宣传大约28个字节的数据。如果事实证明广告自定义数据不可能,我不想开始一个重大项目。
答案 0 :(得分:0)
答案是 - 你可以!如果您通过文档进一步阅读,您将知道如何操作。
完成阅读this和this文档后,我建议您逐行实施Central-Peripheral combo here。
以下是关于如何做到这一点(通过外围触发器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;
}
}
}