蓝牙学习iOS技术集

iOS 蓝牙 5.0 后台扫描

2022-10-04  本文已影响0人  Swift社区

后台长久任务:

#pragma mark APP进入后台触发的方法
- (void)applicationDidEnterBackground:(UIApplication *)application {
    // 进入后台,处理后台任务
    [self comeToBackgroundMode];
}

#pragma mark 处理后台任务
- (void)comeToBackgroundMode {
    self.count = 0;
    // 初始化一个后台任务BackgroundTask,这个后台任务的作用就是告诉系统当前App在后台有任务处理,需要时间
    [self beginBackgroundTask];

}

#pragma mark 开启一个后台任务
- (void)beginBackgroundTask {
    UIApplication *app = [UIApplication sharedApplication];
    self.bgTask = [app beginBackgroundTaskWithExpirationHandler:^{

    }];
    // 开启定时器,不断向系统请求后台任务执行的时间
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(applyForMoreTime) userInfo:nil repeats:YES];

}

#pragma mark 结束一个后台任务
- (void)endBackgroundTask {
    UIApplication *app = [UIApplication sharedApplication];
    [app endBackgroundTask:self.bgTask];
    self.bgTask = UIBackgroundTaskInvalid;
    // 结束计时
    [self.timer invalidate];
}

#pragma mark 申请后台运行时间
- (void)applyForMoreTime {
    self.count ++;
    NSLog(@"%ld,剩余时间:%f", (long)self.count, [UIApplication sharedApplication].backgroundTimeRemaining);

    if (self.count % 150 == 0) {
        dispatch_async(dispatch_get_main_queue(), ^{
            // 结束当前后台任务
            [self endBackgroundTask];
            // 开启一个新的后台任务
            [self beginBackgroundTask];
        });
    }

}

#pragma mark APP进入前台
- (void)applicationWillEnterForeground:(UIApplication *)application {
    // 结束后台任务
    [self endBackgroundTask];
}

说明:这种方法会执行后台任务,但是最多在后台运行3分钟。

APP在后台扫描蓝牙(两种方式)

// self.cbCentralMgr 为蓝牙中心模块
[self.cbCentralMgr scanForPeripheralsWithServices:nil options:nil];
[self.cbCentralMgr scanForPeripheralsWithServices:@[[CBUUID UUIDWithString:@"指定的serviceUUID"]] options:@{CBCentralManagerScanOptionAllowDuplicatesKey:@(YES)}];

遇到的坑

建议
由于苹果的这种特性,建议在前台时扫描蓝牙设备时,设置CBCentralManagerScanOptionAllowDuplicatesKey为NO;在后台扫描蓝牙时,设置CBCentralManagerScanOptionAllowDuplicatesKey为YES

上一篇下一篇

猜你喜欢

热点阅读