核心蓝牙状态恢复

时间:2014-04-06 18:08:31

标签: ios ios7 bluetooth core-bluetooth cbcentralmanager

我正在开发一款应用程序,可以对外围设备的断开做出反应,我现在正在尝试采用iOS 7中引入的ne状态保存和恢复。

我做的就像文档说的那样,意思是:

  1. 我为中心添加了背景模式。

  2. 我总是使用相同的唯一实例化我的中央管理器     标识符。

  3. 我实施了centralManager:willRestoreState:方法。

  4. 当我的应用程序移动到后台时,我使用kill(getpid(), SIGKILL);在AppDelegate回调中将其杀死。 (Core Bluetooth State Preservation and Restoration Not Working, Can't relaunch app into background

    当我现在通过取出电池断开外围设备时,我的应用程序正在按预期唤醒,launchOptions[UIApplicationLaunchOptionsBluetoothCentralsKey]包含正确的标识符但未调用centralManager:willRestoreState:。 只有当我断开另一个外围设备时,才会调用此方法。

1 个答案:

答案 0 :(得分:1)

我就是这样:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{

    NSArray *peripheralManagerIdentifiers = launchOptions[UIApplicationLaunchOptionsBluetoothPeripheralsKey];

    if (peripheralManagerIdentifiers) {

        // We've restored, so create the _manager on the main queue
        _manager = [[CBPeripheralManager alloc] initWithDelegate:self
                                                          queue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
                                                        options:@{CBPeripheralManagerOptionRestoreIdentifierKey:@"YourUniqueIdentifier"}];

    } else {

        // Not restored so just create as normal
        manager = [[CBPeripheralManager alloc] initWithDelegate:self
                                                          queue:nil
                                                        options:@{CBPeripheralManagerOptionRestoreIdentifierKey:@"YourUniqueIdentifier"}];

    }
return YES;
}

然后:

- (void)peripheralManager:(CBPeripheralManager *)peripheral
         willRestoreState:(NSDictionary *)dict
{


    // This is the advertisement data that was being advertised when the app was terminated by iOS
    _advertisementData = dict[CBPeripheralManagerRestoredStateAdvertisementDataKey];

    NSArray *services = dict[CBPeripheralManagerRestoredStateServicesKey];

    // Loop through the services, I only have one service but if you have more you'll need to check against the UUID strings of each
    for (CBMutableService *service in services) {

        _primaryService = service;

        // Loop through the characteristics
        for (CBMutableCharacteristic *characteristic in _primaryService.characteristics) {

            if ([characteristic.UUID.UUIDString isEqualToString:CHARACTERISTIC_UUID]) {

                _primaryCharacteristic = characteristic;

                NSArray *subscribedCentrals = characteristic.subscribedCentrals;

                // Loop through all centrals that were subscribed when the app was terminated by iOS
                for (CBCentral *central in subscribedCentrals) {

                    // Add them to an array
                    [_centrals addObject:central];

                }
            }
        }
    }
}