CoreBluetooth状态保存:恢复CBCentralManager的正确方法

时间:2015-10-14 12:27:43

标签: ios cbcentralmanager ble-state-preservation

当App因状态保存事件而被选中时,从AppDelegate恢复CBCentralManager的正确方法是什么?

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // The system provides the restoration identifiers only for central managers that had active or pending peripheral connections or were scanning for peripherals.
    NSArray * centralManagerIdentifiers = launchOptions[UIApplicationLaunchOptionsBluetoothCentralsKey];

    if (centralManagerIdentifiers != nil) {
        for (int i=0; i<[centralManagerIdentifiers count]; i++) {
            NSString * identifier = [centralManagerIdentifiers objectAtIndex:i];
            NSLog(@"bluetooth central key identifier %@", identifier);
            // here I expect to re-instatiate the CBCentralManager but not sure how and if this is the best place..
        }
    }

    // Override point for customization after application launch.
    return YES;
}

1 个答案:

答案 0 :(得分:1)

当您获得标识符列表时,您必须通过此列表进行迭代,并为每个标识符初始化CBCentralManager的实例。列表包含NSString个对象。

NSArray *centralManagerIdentifiers = launchOptions[UIApplicationLaunchOptionsBluetoothCentralsKey];

for (NSString *centralManagerIdentifier in centralManagerIdentifiers) {
    CBCentralManager *centralManager = [[CBCentralManager alloc] initWithDelegate:self
                                                                            queue:nil
                                                                          options:@{CBCentralManagerOptionRestoreIdentifierKey: centralManagerIdentifier}];

    [self.cenralManagers addObject:centralManager];
}

有关详细信息,请参阅“核心蓝牙编程指南”中的State Preservation and Restoration