As we know, there are some restrictions for applications running in the background. For example, NSTimer does not work. I tried to write a "Timer" like this, which might work in the background.
-(UIBackgroundTaskIdentifier)startTimerWithInterval:(NSTimeInterval)interval run:(void (^)())runBlock complete:(void (^)())completeBlock
{
NSTimeInterval delay_in_seconds = interval;
dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, delay_in_seconds * NSEC_PER_SEC);
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
UIBackgroundTaskIdentifier taskIdentifier = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
completeBlock();
}];
NSLog(@"remain task time = %f,taskId = %d",[UIApplication sharedApplication].backgroundTimeRemaining,taskIdentifier);
dispatch_after(delay, queue, ^{
runBlock();
dispatch_async(dispatch_get_main_queue(), ^{
completeBlock();
[[UIApplication sharedApplication] endBackgroundTask:taskIdentifier];
});
});
return taskIdentifier;
}
I called this function as follows:
-(void)fire
{
self.taskIdentifier = [self startTimerWithInterval:10
run:^{
NSLog(@"timer!");
[self fire];
}
complete:^{
NSLog(@"Finished");
}];
}
This timer works fine except for one problem. The longest period for a background task is 10 minutes. (Refer to NSLog at startTimerWithInterval).
If any way to get my timer to work for more than 10 minutes? By the way, my application is a BLE application, I already installed UIBackgroundModes in bluetooth-central.
source
share