IOS 8: When app is in background CBCentralManager didDiscoverPeripheral, didConnectPeripheral, didFailToConnectPeripheral did not call

I am using Xcode 6 with iOS 8. I am trying to search and connect a bluetooth device while the app is running in the background. I am using frameworkbluetooth framework. I have added bluetooth center and bluetooth peripherals using Xcode's capabilities.

code:

Appdelegate.h

@interface WSAppDelegate : UIResponder <UIApplicationDelegate, UITabBarControllerDelegate,CBCentralManagerDelegate,CBPeripheralDelegate>

@property (strong, nonatomic) NSString *savedUUID;
@property (strong, nonatomic) CBCentralManager *CBCM;

      

AppDelegate.m

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.

    NSUserDefaults *defaults=[[NSUserDefaults alloc] init];
    self.savedUUID= [defaults stringForKey:@"uuid"];

    UIApplication *app = [UIApplication sharedApplication];
    UIBackgroundTaskIdentifier bgTask = 0;
    bgTask = [app beginBackgroundTaskWithExpirationHandler:^{

        NSLog(@"Object Created::::");
         self.CBCM = [[CBCentralManager alloc] initWithDelegate:self queue:nil];


        [app endBackgroundTask:bgTask];
    }];

}


- (void)centralManagerDidUpdateState:(CBCentralManager *)central {
    printf("Status of CoreBluetooth central manager changed \n");

    if(self.CBCM.state == CBCentralManagerStatePoweredOn)
    {
        //okay your good to go and can now scan
        //  NSLog(@"your good to go and can now scan");
        NSLog(@"Searching for Device::::");
        NSUUID *uuid = [[NSUUID alloc]initWithUUIDString:self.savedUUID];//where savedUUID is the string version of the NSUUID you've saved somewhere

        NSArray *peripherals = [self.CBCM retrievePeripheralsWithIdentifiers:@[uuid]];

        for(CBPeripheral *periph in peripherals)
        {
            [self.CBCM connectPeripheral:periph options:nil];
        }
    }
    else
    {
        //Unable to use CentralManager methods so print out the central.state and find out why
        NSLog(@"Unable to use CentralManager methods so print out the central state and find out why:::%d",self.CBCM.state);
    }


}

- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI {

    NSLog(@"Peripheral Found::::%@",peripheral);

}

- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {

    printf("Connection to peripheral with UUID successfull\r\n");

}

- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
    printf("Connection to peripheral with UUID Fail,didFailToConnectPeripheral\r\n");
    printf("Error code was %s\r\n",[[error description] cStringUsingEncoding:NSStringEncodingConversionAllowLossy]);

}

      

The didDiscoverPeripheral method is not called, so I use the saved uuid of the last connected device, but it does not connect and does not call the didConnectPeripheral and didFailToConnectPeripheral delegation methods. So how to solve this problem and connect to bluetooth when the app is running in the background?

+3


source to share


1 answer


I would not use BackgroundTask to scan peripherals in the background.

1) When creating your CBCentralManager, make sure you specify a parameter for the CBCentralManagerOptionRestoreIdentifierKey .

  myCentralManager =
    [[CBCentralManager alloc] initWithDelegate:self queue:nil
     options:@{ CBCentralManagerOptionRestoreIdentifierKey:
     @"myCentralManagerIdentifier" }];

      

Cm:

https://developer.apple.com/library/ios/documentation/NetworkingInternetWeb/Conceptual/CoreBluetooth_concepts/CoreBluetoothBackgroundProcessingForIOSApps/PerformingTasksWhileYourAppIsInTheBackground.html#//apple_refTP71325/Wid



2) Look for UIApplicationLaunchOptionsBluetoothCentralsKey in the AppDelegate doneFinishLaunchingWithOptions launchOptions:

NSArray *centralManagerIdentifiers =
    launchOptions[UIApplicationLaunchOptionsBluetoothCentralsKey];

      

This is used to restore the central manager. (There will be the same name for the key in 1).

3) Make sure you are doing willRestoreState in your CBCentralManagerDelegate. See the Documentation above.

0


source







All Articles