バックグラウンドタスクが10分を超えて実行された場合、タスクは一時停止され、beginBackgroundTaskWithExpirationHandlerで指定されたコードブロックが呼び出されてタスクがクリーンアップされます。バックグラウンドの残り時間は、[[UIApplicationsharedApplication]backgroundTimeRemaining]で確認できます。最初にアプリがフォアグラウンドにあるとき、backgroundTimeRemainingはより大きな値に設定されます。アプリがバックグラウンドに移行すると、backgroundTimeRemainingの値が599.XXX(10分)から減少することがわかります。backgroundTimeRemainingがZEROになると、バックグラウンドタスクは一時停止されます。
//1)Creating iOS Background Task
__block UIBackgroundTaskIdentifier background_task;
background_task = [application beginBackgroundTaskWithExpirationHandler:^ {
//This code block is execute when the application’s
//remaining background time reaches ZERO.
}];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//### background task starts
//#### background task ends
});
//2)Making background task Asynchronous
if([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)])
{
NSLog(@"Multitasking Supported");
__block UIBackgroundTaskIdentifier background_task;
background_task = [application beginBackgroundTaskWithExpirationHandler:^ {
//Clean up code. Tell the system that we are done.
[application endBackgroundTask: background_task];
background_task = UIBackgroundTaskInvalid;
}];
**//Putting All together**
//To make the code block asynchronous
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//### background task starts
NSLog(@"Running in the background\n");
while(TRUE)
{
NSLog(@"Background time Remaining: %f",[[UIApplication sharedApplication] backgroundTimeRemaining]);
[NSThread sleepForTimeInterval:1]; //wait for 1 sec
}
//#### background task ends
//Clean up code. Tell the system that we are done.
[application endBackgroundTask: background_task];
background_task = UIBackgroundTaskInvalid;
});
}
else
{
NSLog(@"Multitasking Not Supported");
}