首先感谢您在 AirFlow RAOP 方面的出色工作,这是一件非常困难的事情!
所以你可以做的是
1.创建一个后台任务处理程序作为dispatch_block_t,比方说
dispatch_block_t myDummyBackgroundTaskBlock = {
[[UIApplication sharedApplication] endBackgroundTask:myDummyBackgroundTask];
myDummyBackgroundTask = UIBackgroundTaskInvalid;
myDummyBackgroundTask = [app beginBackgroundTaskWithExpirationHandler:myDummyBackgroundTask];
};
2. 在某处定义此后台和前台任务处理程序
// foreground
-(void)handleTasksForApplicationInForeground {
if(myDummyBackgroundTask) { // reset that task
[[UIApplication sharedApplication] endBackgroundTask: myDummyBackgroundTask];
myDummyBackgroundTask = UIBackgroundTaskInvalid;
}
}
// background
-(void) handleTasksForApplicationInBackground {
UIDevice *device = [UIDevice currentDevice];
BOOL backgroundSupported = NO;
if ([device respondsToSelector:@selector(isMultitaskingSupported)])
backgroundSupported = device.multitaskingSupported;
if(backgroundSupported && backgroundEnabled) { // perform a background task
myDummyBackgroundTaskBlock = ^{
[[UIApplication sharedApplication] endBackgroundTask: myDummyBackgroundTaskBlock];
myDummyBackgroundTaskBlock = UIBackgroundTaskInvalid;
};
SEL sel = @selector(doDummyBackgroundTask);
[self doBackgroundTaskAsync:sel];
[self performSelector:@selector(doBackgroundTaskAsync:) withObject:nil afterDelay:500.0f]; /// LP: this is the funny part since iOS will kill the task after 500 sec.
}
}
3.现在让我们在应用程序中处理委托后台模式(如之前定义的那样,您可以在应用程序.plist中使用不同的选项激活后台模式):
-(void)applicationDidEnterBackground:(UIApplication *)application {
[self handleTasksForApplicationInBackground];
}
-(void)applicationWillEnterForeground:(UIApplication *)application {
[self handleTasksForApplicationInForeground];
}
4. 看看后台异步任务选择器做了什么
-(void) doBackgroundTaskAsync:(SEL)selector {
@try {
if( [[UIApplication sharedApplication] backgroundTimeRemaining] < 5 ) {
return;
}
if(!myDummyBackgroundTaskBlock) { // need to create again on-the-fly
myDummyBackgroundTaskBlock = ^{
[[UIApplication sharedApplication] endBackgroundTask:myDummyBackgroundTask];
myDummyBackgroundTask = UIBackgroundTaskInvalid;
};
}
myDummyBackgroundTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:myDummyBackgroundTaskBlock];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
while ([[UIApplication sharedApplication] backgroundTimeRemaining] > 5.0) {
int delta = 5.0;
[self performSelector: selector ];
sleep(delta);
}
});
}
@catch (...) {
}
}
我知道这个解决方案效果很好,但我知道有时 iOS 无论如何都会终止应用程序后台任务。无论如何,如果用户突然在前台和后台之间切换应用程序,它将无限期地工作。