ios - CoreBluetooth 背景 - 如何重新实例化 appdelegate 中的中央管理器对象?

标签 ios objective-c bluetooth core-bluetooth

我正在使用 CoreBluetooth 制作一个应用程序,我希望它在后台运行并执行与蓝牙相关的任务。

谁能解释一下如何在 appdelegate 中重新实例化中央管理器对象?

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    NSArray *centralManagerIdentifiers = launchOptions[UIApplicationLaunchOptionsBluetoothCentralsKey];

    for (NSString *identifier in centralManagerIdentifiers) {

      if ([identifier isEqualToString:@"myCentral"]) {

      // what to do here?

      }
}

最佳答案

我假设您想要按照 "Reinstantiate Your Central and Peripheral Managers" section of the documentation 中的描述在您的应用委托(delegate)中恢复多个中心。 ?

如果是这样,我可以看到 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;
}

您可能不想像我在此示例中那样在应用程序委托(delegate)中保留对所有中心的引用,也不一定要让您的应用程序委托(delegate)充当中心的 CBCentralManagerDelegate,但您明白了......

关于ios - CoreBluetooth 背景 - 如何重新实例化 appdelegate 中的中央管理器对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21992058/

相关文章:

iOS Per-App VPN 未连接到互联网

ios - 如何更改默认触摸 ID 警报的触摸 ID 警报图标?

objective-c - 动态创建一个NSString stringWithFormat : output

ios - 在没有 textField 的情况下捕获文本输入

android - 创建新 Ionic 项目时运行子过程电容器时发生错误

iOS - 完整上传带有 EXIF 的图像

objective-c - 通过 OSX 辅助功能 API 获取窗口编号

Android 2.1蓝牙SPP转LM058(串口线更换)问题

android - Rxandroid ble 重连处理指南

ios - Xcode 6.2 - 'as' 之后的预期类型