iOS 8:当后台应用程序CBCentralManager委托方法didDiscoverPeripheral,didConnectPeripheral,didFailToConnectPeripheral未调用时

时间:2014-11-04 09:28:27

标签: ios ios8 background-process core-bluetooth

我在iOS 8中使用Xcode 6.我正在尝试在应用程序在后台运行时搜索并连接蓝牙设备。我正在使用corebluetooth框架。我使用Xcode功能选项添加了bluetooth-central和bluetooth-peripheral。

代码:

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

}

didDiscoverPeripheral方法没有被调用所以我使用保存的最后连接设备的uuid但它没有连接而且没有调用委托方法didConnectPeripheral和didFailToConnectPeripheral。 那么如何解决这个问题并在应用程序在后台运行时与蓝牙连接?

1 个答案:

答案 0 :(得分:0)

我不会使用BackgroundTask在后台扫描外围设备。

1)创建CBCentralManager时,请确保为 CBCentralManagerOptionRestoreIdentifierKey 指定选项。

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

请参阅:

https://developer.apple.com/library/ios/documentation/NetworkingInternetWeb/Conceptual/CoreBluetooth_concepts/CoreBluetoothBackgroundProcessingForIOSApps/PerformingTasksWhileYourAppIsInTheBackground.html#//apple_ref/doc/uid/TP40013257-CH7-SW6

2)在AppDelegate的didFinishLaunchingWithOptions方法的launchOptions中查找UIApplicationLaunchOptionsBluetoothCentralsKey:

NSArray *centralManagerIdentifiers =
    launchOptions[UIApplicationLaunchOptionsBluetoothCentralsKey];

这用于恢复您的中央管理员。 (与1中的密钥名称相同)。

3)确保在CBCentralManagerDelegate中实现willRestoreState。请参阅上面列出的文档。