2014-04-06 158 views
0

我的工作是在外設上的斷開反應的程序,現在我試圖採用NE狀態保存和恢復的iOS推出7核心藍牙狀態恢復

我不喜歡的文件說的一切,手段:

  1. 我爲中央添加了背景模式。

  2. 我總是使用相同的唯一 標識符實例化我的中央管理器。

  3. 我執行centralManager:willRestoreState:方法。

當我的應用程序移動到後臺時,我在AppDelegate回調中用kill(getpid(), SIGKILL);殺死它。 (Core Bluetooth State Preservation and Restoration Not Working, Can't relaunch app into background

當我現在通過刪除電池斷開外圍設備時,我的應用正在按預期方式被喚醒,並且launchOptions[UIApplicationLaunchOptionsBluetoothCentralsKey]包含正確的標識符,但centralManager:willRestoreState:未被調用。 只有當我斷開另一個外設時,這個方法纔會被調用。

+0

藍牙行爲有時很奇怪。這也發生在我身上,重新啓動設備,突然它工作。此外,您的應用程序在被殺之前最後一件事情可能需要掃描或嘗試連接外設。 – Yazid

+0

雖然您需要再次實例化中央管理器,否則willRestoreState:將不會被調用。 – OutOnAWeekend

回答

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]; 

       } 
      } 
     } 
    } 
} 
+0

我看到你正在初始化應用程序委託中央管理器,但是ifcentral管理器在不同的類中呢?我有中央經理的共享管理器。 – Paragon