在应用程序进入后台后,您可以使用后台任务运行应用程序长达十分钟。查看 iOS App Programming Guide 的Background Execution and Multitasking部分。
- (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];
}