修改 关注@RobertVaessen评论我实现了以下内容,但是我仍然无法发现连接外围设备的服务。
-(void) centralManager:(CBCentralManager *)central willRestoreState:(NSDictionary<NSString *,id> *)dict{
id tmpObj = [dict objectForKey:CBCentralManagerRestoredStatePeripheralsKey];
NSArray * keys = [dict allKeys];
NSString * message = @"";
for (int i=0; i<[keys count]; i++) {
NSString * stringTmp = keys[i];
message = [message stringByAppendingString:@";"];
message = [message stringByAppendingString:stringTmp];
}
// message contains "kCBRestoredScanServices and kCBRestoredPeripherals
if ([tmpObj isKindOfClass:[NSArray class]]) {
NSArray * peripheralsArray = (NSArray*)tmpObj;
for (int i=0; i<[peripheralsArray count]; i++) {
id objTmp = peripheralsArray[i];
if ([objTmp isKindOfClass:[CBPeripheral class]]) {
CBPeripheral * tmpPeripheral = (CBPeripheral*)objTmp;
tmpPeripheral.delegate = self;
[tmpPeripheral discoverServices: self.bleServices];
// It would reach this part of the code but not discover any services
}
}
}
}
现在的疑问是:
当应用程序处于前台并首次连接到外围设备时,我已经发现了服务,这是否意味着一旦应用程序再次唤醒应用程序,CBCentralManager将无法发现服务?
理论背景:
此处描述了蓝牙LE状态保存过程(参见部分“添加对状态保存和恢复的支持”):
我要做的是:
我正在实施一个使用 BLE状态保存的应用来维持与硬件配件的连接(在后台运行时)。
我得到的问题是,每当 iOS在BLE状态保存事件后唤醒我的应用程序时,我的CBCentralManager无法发现服务。 奇怪的是,硬件外围设备“看到”了连接,但iOS应用程序无法访问它。
换句话说: 实现CBCentralManager委托的类中的以下方法被正确调用但没有做太多(参见下面的绿色注释):
-(void) centralManager:(CBCentralManager *)central willRestoreState:(NSDictionary<NSString *,id> *)dict{
NSArray * peripherals = [self.central retrieveConnectedPeripheralsWithServices:self.bleServices];
for (int i=0; i < peripherals.count; i++) {
CBPeripheral * peripheral = (CBPeripheral*) peripherals[i];
if (peripheral == nil) {
// Never happens
}
else{
// Always happens - also hardware thinks that the peripheral is connected
peripheral.delegate = self;
[peripheral discoverServices:self.bleServices];
// Does not discover any services ! <------------- ERROR!
}
}
-(void) peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error {
// Only gets called when [peripheral discoverServices:self.bleServices] is called whilst app is running (either in background or foreground).
}
PS:我也问了这个in the Apple Developer论坛,但到目前为止还没有回复。
PPS: 我还在info.plist文件中激活了后台模式: