我有一个应用程序,它扮演外围角色并使用 CoreBluetooth 框架启动广告。我成功添加了一个服务并对其进行了广告,并使用另一个Central应用程序成功发现了它。
但是,当我想向我的主服务添加一些辅助服务时,其他中央应用程序不会发现它们。
在外围设备上,我将服务添加到CBPeripheralManager
对象:
- (void)AddService:(BOOL )primary {
CBMutableService *Service = [[CBMutableService alloc] initWithType:_service_UUID primary:primary];
if (primary)
_mainService = Service;
NSMutableArray *characteristics = [[NSMutableArray alloc] init];
for (MyCharacterstic *characteristic in _service_characteristics)
[characteristics addObject: [characteristic GetObject]];
Service.characteristics = characteristics;
[_manager addService: Service];
}
- (void)peripheralManager:(CBPeripheralManager *)peripheral didAddService:(CBService *)service error:(NSError *)error {
if (!service.isPrimary)
[_services addObject:service];
}
添加完所有辅助服务后,我调用以下函数开始播放:
- (void)StartAdvertisement {
_mainService.includedServices = _services;
[_manager startAdvertising:@{CBAdvertisementDataLocalNameKey: _LocalName,
CBAdvertisementDataServiceUUIDsKey: @[_mainService.UUID]}];
}
在中心端,我尝试发现所包含的服务:
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error {
for (CBService *service in peripheral.services) {
if ([_service_UUID containsObject: service.UUID]) {
[peripheral discoverCharacteristics:nil forService:service];
[peripheral discoverIncludedServices:nil forService:service];
}
}
}
它调用以下委托函数,但它总是为包含的服务返回一个空数组:
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverIncludedServicesForService:(CBService *)service error:(NSError *)error {
for (CBService *services in service.includedServices) {
NSLog(@"Service: %@", services);
}
}