核心蓝牙后台 - 如何在应用程序委托中重新实例化中央管理器对象



我正在使用CoreBlue软件开发一个应用程序,我希望它在后台运行并执行与蓝牙相关的任务。

有人可以解释我如何在应用程序委托中重新实例化中央管理器对象吗?

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    NSArray *centralManagerIdentifiers = launchOptions[UIApplicationLaunchOptionsBluetoothCentralsKey];
    for (NSString *identifier in centralManagerIdentifiers) {
      if ([identifier isEqualToString:@"myCentral"]) {
      // what to do here?
      }
}

我假设您想按照文档的"重新实例化您的中央和外围管理器"部分所述,在应用程序委托中恢复多个中心?

如果是这样,我可以看到didFinishLaunchingWithOptions看起来像这样:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.referencesToCentrals = [NSMutableArray array];
    NSArray *centralManagerIdentifiers = launchOptions[UIApplicationLaunchOptionsBluetoothCentralsKey];
    if ((centralManagerIdentifiers) && (centralManagerIdentifiers.count > 0)) {
        // The system knows about one or more centrals that need to be restored.
        for (NSString *identifier in centralManagerIdentifiers) {
            CBCentralManager *manager = [[CBCentralManager alloc] initWithDelegate:self queue:nil options:@{CBPeripheralManagerOptionRestoreIdentifierKey : identifier}];
            [self.referencesToCentrals addObject:manager];
        }
    }
    else {
        // No centrals need to be restored.  If desired, create one for use and save a reference like this:
        CBCentralManager *manager = [[CBCentralManager alloc] initWithDelegate:self queue:nil options:@{CBPeripheralManagerOptionRestoreIdentifierKey : [[NSUUID UUID] UUIDString]}];
        [self.referencesToCentrals addObject:manager];
    }
    // Set up window, etc...
    return YES;
}

你可能不想像我在这个例子中所做的那样在应用程序委托中保留对所有中心的引用,也不一定让你的应用委托充当中心的 CBCentralManagerDelegate,但你明白了......

最新更新