简体   繁体   中英

Keep an iOS app running in foreground

I would like to know if there's a way to keep an app running in foreground, during a specific interval time.

I have a thread running exactly during 3 minutes and I need that the user cannot leave the app. If such a thing is not possible I'm going to ask another question.

I could let that the user set the app in background mode because I use the applicationDidEnterBackground:(UIApplication *)application method to save the data I need but if the user clicks the power button, how could I save the data?

The applicationWillTerminate:(UIApplication *)application would be called? Is there any solution?

You might want to look into beginBackgroundTaskWithExpirationHandler , which lets your app request additional processing time to complete tasks when your app is backgrounded.

That said, what you're looking to do isn't advisable. You should make sure your app can recover from your three minute task in case of unexpected termination or failure. For example, your app could crash unexpectedly or terminate due to low memory - in these cases, you won't get any callbacks to applicationWillTerminate or applicationDidEnterBackground .

So my recommendation would be to look at using iOS's background task support to have your save continue in the background if the user leaves the app, but also ensure that in the event your app be terminated by the system without warning your task is recoverable / can safely be rewound.

You need to use beginBackgroundTaskWithExpirationHandler to handle your process alive. use this code.

Here I called this method from applicationDidEnterBackground:(UIApplication *)application to store the data in SQlite even the application enter background or UIApplicationStateInactive (press power button). Saving process will continue for 10 mins as per the IOS standard if application.backgroundTimeRemaining comes to 0 I will post one local notification to bring up my application to foreground to keep my process alive. use this code and customize your process.

-(void)handleBackgroundSavingingProcess:(UIApplication *)application
    {
        NSLog(@"background task remaining time before background %f",application.backgroundTimeRemaining);

        if ((([application applicationState] == UIApplicationStateBackground) || ([application applicationState] == UIApplicationStateInactive)) && [application respondsToSelector:@selector(beginBackgroundTaskWithExpirationHandler:)])
  {


     self.bgTaskId = [application beginBackgroundTaskWithExpirationHandler:^{
     // Synchronize the cleanup call on the main thread in case
     // the task actually finishes at around the same time.
                NSLog(@"background task remaining time in expiration handler %f",application.backgroundTimeRemaining);

                dispatch_queue_t concurrentQueue;
                if([[[UIDevice currentDevice] systemVersion] doubleValue] >= 5.0)
                    concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0UL);
                else
                    concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0UL);

                if (concurrentQueue == nil)
                    return;

                dispatch_async(concurrentQueue, ^{

                    if (self.bgTaskId != UIBackgroundTaskInvalid){
                        NSLog(@"background task remaining time in dispatch queue %f",application.backgroundTimeRemaining);
                        NSLog(@" Downloading status %d",self.isDownloadingInComplete);
                        if(self.isDownloadingInComplete)
                        {
                            [application presentLocalNotificationNow:localNotification];
                            NSLog(@"Local notification fired.");
                        }
                        [DataManager managedObjectContext] save:nil];
                        [application endBackgroundTask:self.bgTaskId];
                        self.bgTaskId = UIBackgroundTaskInvalid;
                        NSLog(@"Initialization invalid.");
                    }
                });
            }];
        }

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM