编辑: 在@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:我也在苹果开发者论坛上问过这个问题,但到目前为止还没有回复。
PPS: 我还在 info.plist 文件中激活了后台模式: