0

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.

Srivathsa
  • 606
  • 10
  • 34

1 Answers1

0

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.

Stavash
  • 14,244
  • 5
  • 52
  • 80
  • First of all thanks for your quick reply. If I perform the synchronous clean up task in the background, I see blank screen when user brings the application to foreground quickly before clean up completed. Thats the reason I am using GCD. Also from lot of googling I found the above approach to use GCD. Help me If I am doing anything wrong. – Srivathsa Aug 10 '13 at 11:09