You can run your app for up to ten minutes after the app went into the background using a background task. Take a look at the Background Execution and Multitasking section of the iOS App Programming Guide.
- (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;
});
}
You can notify the user by sending a UILocalNotification
:
- (void)notifyUserWhilePerformingBackgroundTask
{
UILocalNotification *notification = [[UILocalNotification alloc] init];
notification.alertBody = @"Headphone removed!";
[[UIApplication sharedApplication] presentLocalNotificationNow:notification];
}