无法在 iOS 上恢复蓝牙状态

Unable to restore bluetooth state on iOS

几周来我一直在努力弄清楚 iOS 中 Core Bluetooth 的状态保存和恢复是如何工作的,但我完全迷失了。

到目前为止,我已经完成了以下工作:

向我的 CBCentralManager 添加了恢复标识符

        centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil   options:@{CBCentralManagerOptionRestoreIdentifierKey:@"myCentralManager"}];

这应该使我的应用程序能够调用委托方法:

centralManager:(CBCentralManager *)central
  willRestoreState:(NSDictionary *)dict;

在这里我尝试重新连接到我的外围设备,如果我在应用程序暂停之前有连接,否则我将尝试再次扫描我的外围设备,如下所示:

if (dict[CBCentralManagerRestoredStatePeripheralsKey]) {
    for (CBPeripheral *currentPeripheral in peripherals) {
        peripheral = currentPeripheral;
    }
    // Connect to peripheral
}
else{
    // Scan for UUID
}

我这样做对吗,我接近了,还是完全错了?

现在对我有用了。 我初始化我的中央管理器,就像我最初做的那样,然后在 willRestoreState 方法中,我 运行 以下代码:

NSArray* peripherals = [central retrieveConnectedPeripheralsWithServices:[NSArray arrayWithObject:UUID]];
if ([peripherals count] > 0) {
    _discoveredPeripheral = [peripherals objectAtIndex:0];
    _discoveredPeripheral.delegate= self;
    [central connectPeripheral:_discoveredPeripheral options:nil];
} else {
[self scan];
}