How to add background infinite timer with background mode BLE Central in IOS?

情到浓时终转凉″ 提交于 2019-12-11 10:37:29

问题


I want to keep my app can fire timer at specific time even when in background,now my app use BLE Central background mode, and I need to send some data to blue peripheral at a specific time, how to implement this? Now the timer selector seems can only be fired when enter back to foreground. I use Xcode 6.3, tested both on iOS 8.1.3 and iOS 8.3.


回答1:


But the timer selector seems can only be fired when app become foreground again. Should I use dispatch_after instead of nstimer?But the dispatch_after can not be canceled once it is scheduled.




回答2:


To allow to work your timer in background mode, you need to enable Uses Bluetooth LE accessories flag ON(Path : Go to target --> capabilities --> Background Modes). like as below.

And add following code in your project to run timer in background:

Step 1: Declare __block UIBackgroundTaskIdentifier bgTask as global variable.

Step 2: To add following code in applicationDidEnterBackground.

- (void)applicationDidEnterBackground:(UIApplication *)application {


     bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
     bgTask = UIBackgroundTaskInvalid;
      }];

}

Step 3: Stop background task handler once apps come in foreground mode.

 - (void)applicationWillEnterForeground:(UIApplication *)application {
  // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.

  [[UIApplication sharedApplication] endBackgroundTask:bgTask];


}



回答3:


I have the problem with my existing application. iOS not allow to run the timer in background even if you have enable the background mode for BLE. It allow only for “Airplay, Airdrop, Picture in Picture” background mode. BLE background mode only used for to make it continue connection. But in iOS v12.0 BLE disconnection event not trigger if your app have in background around 2 to 3 hrs. But it perfectly working fine on older versions.



来源:https://stackoverflow.com/questions/29669156/how-to-add-background-infinite-timer-with-background-mode-ble-central-in-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!