バックグラウンド タスクを使用して、アプリがバックグラウンドになった後、最大 10 分間アプリを実行できます。iOS アプリ プログラミング ガイドの「バックグラウンド実行とマルチタスク」セクションをご覧ください。
- (void)applicationDidEnterBackground:(UIApplication *)application
{
backgroundTask = [application beginBackgroundTaskWithExpirationHandler:^{
// clean up any unfinished task business, your app is going to be killed if you don't end the background task now
[application endBackgroundTask:backgroundTask];
backgroundTask = UIBackgroundTaskInvalid;
}];
// start the long-running task and return immediately.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// Monitor the head phone jack here.
// If this happens asynchronously, you don't need to dispatch this block, your app will continue to run as normal, only modifying or accessing its UI while it's in background mode is prohibited.
// End the background task if you're done. If this is never the case, your expiration handler will be called after ten minutes.
[application endBackgroundTask:backgroundTask];
backgroundTask = UIBackgroundTaskInvalid;
});
}
次のメッセージを送信して、ユーザーに通知できますUILocalNotification
。
- (void)notifyUserWhilePerformingBackgroundTask
{
UILocalNotification *notification = [[UILocalNotification alloc] init];
notification.alertBody = @"Headphone removed!";
[[UIApplication sharedApplication] presentLocalNotificationNow:notification];
}