Core Bluetooth Background Processing for iOS Apps

叶冥夜
2023-12-01

之前做了一个蓝牙的项目,但该项目的特点是,并不进行连接动作,而是始终依靠外设的广播去更新IOSUI,获得一些数据进行处理,当设备在前台时,处理没有问题,并且能扫描到多台外设:


NSDictionary* scanOptions = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:CBCentralManagerScanOptionAllowDuplicatesKey];

    

    // Make sure we start scan from scratch

    [self.cm stopScan];

    

    [self.cm scanForPeripheralsWithServices:nil options:scanOptions];


IOS支持在APP进入后台后的蓝牙通讯,但是对于扫描设备,在进入后台后,为了进行省电,则做了处理。正如苹果文档所描述如下:


The bluetooth-central Background Execution Mode

When an app that implements the central role includes the UIBackgroundModes key with thebluetooth-central value in itsInfo.plist file, the Core Bluetooth framework allows your app to run in the background to perform certain Bluetooth-related tasks. While your app is in the background you can still discover and connect to peripherals, and explore and interact with peripheral data. In addition, the system wakes up your app when any of theCBCentralManagerDelegate orCBPeripheralDelegate delegate methods are invoked, allowing your app to handle important central role events, such as when a connection is established or torn down, when a peripheral sends updated characteristic values, and when a central manager’s state changes.

Although you can perform many Bluetooth-related tasks while your app is in the background, keep in mind that scanning for peripherals while your app is in the background operates differently than when your app is in the foreground. In particular, when your app is scanning for device while in the background:

  • The CBCentralManagerScanOptionAllowDuplicatesKey scan option key is ignored, and multiple discoveries of an advertising peripheral are coalesced into a single discovery event.
  • If all apps that are scanning for peripherals are in the background, the interval at which your central device scans for advertising packets increases. As a result, it may take longer to discover an advertising peripheral.

These changes help minimize radio usage and improve the battery life on your iOS device.

当进入后台后,只能从原先的多重发现变为单一设备发现,并且要指定该设备的UUID及service UUID。


[self.cm scanForPeripheralsWithServices:@[[CBUUID UUIDWithString:@"1809"]]

                                        options:@{

                                                  CBCentralManagerScanOptionSolicitedServiceUUIDsKey:@[

                                                          [CBUUID UUIDWithString:[USER_DEFAULT objectForKey:KEY_SELECED_FOB]]]}];


于是当APP进入后台后,起定时器进行循环扫描:


- (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.

    NSLog(@"Saving all fobs...");

    

    NSError *error;

    if (![self.managedObjectContext save:&error])

    {

        NSLog(@"Saving failed: %@", error);

    }

    if (!_scanTimer&&[USER_DEFAULT boolForKey:KEY_BACKGROUND_OPEN]) {

        _scanTimer = [NSTimer timerWithTimeInterval:1.0f target:self selector:@selector(backgroundScanBle) userInfo:nil repeats:YES];

        [[NSRunLoop currentRunLoop]addTimer:_scanTimer forMode:NSRunLoopCommonModes];

    }

}

要确认该设备的广播中包含了service uuid的字段


data: {

    kCBAdvDataChannel = 37;

    kCBAdvDataIsConnectable = 0;

    kCBAdvDataLocalName = unova;

    kCBAdvDataServiceData =     {

        Battery = <64>;

        1809 = <860a00fe>;

    };

    kCBAdvDataServiceUUID = 1809;


    kCBAdvDataTxPowerLevel = 5;

}, RSSI: -77.000000, peripheral.identifier:<__NSConcreteUUID 0x17ec2f60> F37D9244-B190-C0FB-AFD5-9254D1B5C108


这样就可以在APP进入后台后 任然能搜到该设备的广播。

相关文章推荐:
http://blog.shiqichan.com/ios-ble-background-central-scanning/

苹果官方:

Core Bluetooth Background Processing for iOS Apps


 类似资料:

相关阅读

相关文章

相关问答