Question

I have to perform a long running clean up operation while application going into background. As the clean up operation is a network transaction and will take more than 5 seconds I am using beginBackgroundTaskWithExpirationHandler: API and everything is working very much fine.

Below I am adding the code for better clarity..

- (void)applicationDidEnterBackground:(UIApplication *)application {

    @synchronized(self)
    {        
        bgTask = [application beginBackgroundTaskWithExpirationHandler:^{

            [application endBackgroundTask:bgTask];
            bgTask = UIBackgroundTaskInvalid;
        }];

        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
            [self performCleanUpOperation];

            [application endBackgroundTask:bgTask];
            bgTask = UIBackgroundTaskInvalid;
        });
    }
}

- (void) performCleanUpOperation
{
    // Cleanup Network Operation 

    [(NSObject *)self performSelectorOnMainThread:(@selector(cleanUpDidFinish)) withObject:nil waitUntilDone:NO];
}

- (void) cleanUpDidFinish
{
    dispatch_async(dispatch_get_main_queue(), ^(void){

        [self saveContext];

        [(CustomUIApplication *)[UIApplication sharedApplication] logoutWithAlert:NO];

        [[UIApplication sharedApplication] endBackgroundTask:bgTask];
        bgTask = UIBackgroundTaskInvalid;
    });
}

Now the problem I am facing is, when I bring application to foreground I am seeing the old screen which the app was before going into background. And immediately navigating to Login screen from old screen.

Any idea why it is not showing login screen when application relaunches, even I have loaded Login ViewController inside cleanUpDidFinish.

Was it helpful?

Solution

The code you've written after beginBackgroundTaskWithExpirationHandler will not get a chance to execute because it is performed asynchronously. Tasks declared as background tasks need to be synchronous in order to get executed the way you expect them to here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top