后臺長久任務:
- 打開后臺模式中的使用藍牙功能(手機為中心模式):TARGET→Capabilities→Background Modes→Uses Bluetooth LE accessories(勾選)
- 在AppDelegate.m中添加下面代碼:
#pragma mark APP進入后臺觸發(fā)的方法
- (void)applicationDidEnterBackground:(UIApplication *)application {
// 進入后臺,處理后臺任務
[self comeToBackgroundMode];
}
#pragma mark 處理后臺任務
- (void)comeToBackgroundMode {
self.count = 0;
// 初始化一個后臺任務BackgroundTask莉撇,這個后臺任務的作用就是告訴系統(tǒng)當前App在后臺有任務處理害晦,需要時間
[self beginBackgroundTask];
}
#pragma mark 開啟一個后臺任務
- (void)beginBackgroundTask {
UIApplication *app = [UIApplication sharedApplication];
self.bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
}];
// 開啟定時器特铝,不斷向系統(tǒng)請求后臺任務執(zhí)行的時間
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];
}
說明:這種方法會執(zhí)行后臺任務壹瘟,但是最多在后臺運行3分鐘鲫剿。
APP在后臺掃描藍牙(兩種方式)
- 第一種方式:掃描所有藍牙設備
// self.cbCentralMgr 為藍牙中心模塊
[self.cbCentralMgr scanForPeripheralsWithServices:nil options:nil];
- 第二種方式:掃描指定serviceUUID藍牙設備
[self.cbCentralMgr scanForPeripheralsWithServices:@[[CBUUID UUIDWithString:@"指定的serviceUUID"]] options:@{CBCentralManagerScanOptionAllowDuplicatesKey:@(YES)}];
遇到的坑
坑一:由于蘋果的限制,使用第一種方式掃描稻轨,APP在后臺運行時是掃描不到任何信息的灵莲;如果想在后臺掃描藍牙設備,必須使用第二種方式殴俱;
坑二:使用第二種方式需要注意政冻,如果設置CBCentralManagerScanOptionAllowDuplicatesKey的值為NO,在后臺調用掃描時只能线欲,掃描到一次明场,即使藍牙廣播的數據有變化,也不會接收到新的廣播
坑三:使用第二種方式李丰,即使CBCentralManagerScanOptionAllowDuplicatesKey如果設置為YES苦锨,會持續(xù)接收到藍牙發(fā)出的廣播,但是接收到的藍牙廣播的內容是不會變的;(這里蘋果是不推薦我們設置為YES舟舒,因為這對手機的電量消耗等是有影響的拉庶,但是在某些特定的場景下我們是必須這樣做的)
坑四:即使我們使用第二種方式掃描,也設置了CBCentralManagerScanOptionAllowDuplicatesKey為YES秃励,但是如果超過三分鐘掃描不到任何藍牙設備氏仗,后臺任務一樣會停止。
建議
由于蘋果的這種特性夺鲜,建議在前臺時掃描藍牙設備時皆尔,設置CBCentralManagerScanOptionAllowDuplicatesKey為NO;在后臺掃描藍牙時谣旁,設置CBCentralManagerScanOptionAllowDuplicatesKey為YES