In the iOS system, the foreground and background operations of the App are different. The iOS operating system imposes many restrictions on background operations, so that the system can run more processes and save power.
The App status is as follows:
For background running, you must first determine whether the device supports multiple tasks and whether there is no way to perform multiple tasks before iOS4.0. However, there are currently few iOS4.0 devices.
UIDevice* device = [UIDevice currentDevice]; BOOL backgroundSupported = NO; if ([device respondsToSelector:@selector(isMultitaskingSupported)]) backgroundSupported = device.multitaskingSupported;
First, useBeginBackgroundTaskWithExpirationHandler: InCall in applicationDidEnterBackground
- (void)applicationDidEnterBackground:(UIApplication *)application{ // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. bgTask = [application beginBackgroundTaskWithExpirationHandler:^{ // Clean up any unfinished task business by marking where you // stopped or ending the task outright. [application endBackgroundTask:bgTask]; bgTask = UIBackgroundTaskInvalid; }]; // Start the long-running task and return immediately. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ // Do the work associated with the task, preferably in chunks. // your code NSLog(@" %f",application.backgroundTimeRemaining); [application endBackgroundTask:bgTask]; bgTask = UIBackgroundTaskInvalid; });}Second, use local system notifications
- (void)scheduleAlarmForDate:(NSDate*)theDate { UIApplication* app = [UIApplication sharedApplication]; NSArray* oldNotifications = [app scheduledLocalNotifications]; // Clear out the old notification before scheduling a new one. if ([oldNotifications count] > 0) [app cancelAllLocalNotifications]; // Create a new notification. UILocalNotification* alarm = [[UILocalNotification alloc] init]; if (alarm) { alarm.fireDate = theDate; alarm.timeZone = [NSTimeZone defaultTimeZone]; alarm.repeatInterval = 0; alarm.soundName = @"alarmsound.caf"; alarm.alertBody = @"Time to wake up!"; [app scheduleLocalNotification:alarm]; } }
The third method is to call the backend running tasks specified by the system, such as GPS music.
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.baidu.com"]]; NSError *error; NSURLResponse *response; NSData *data= [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
Response can be normally received, and a problem is solved temporarily. However, execution efficiency is a problem for several requests.