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.