Search code examples
iosobjective-cbackground-process

backgroundTask not finishing in iOS


I have the following code which makes a call to the server, before the app is about to exit. My problem is, that the code sometimes works, sometimes not. Mostly not. Here is the code:

//Set the user as in-active if app is force closed
- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.

    NSLog(@"called");

    bgTask = [application beginBackgroundTaskWithName:@"setInActive" expirationHandler:^{
        [application endBackgroundTask:bgTask];
        bgTask = UIBackgroundTaskInvalid;

    }];

    // Start the long-running task and return immediately.
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        NSLog(@"disp called");

        //If the app is about to exit make the user inactive
        [[APIManager sharedInstance] setInActiveOnCompletion:^(BOOL finished){
            [application endBackgroundTask:bgTask];
            bgTask = UIBackgroundTaskInvalid;
        }];

    });

}

The first NSLog gets called everytime. However the second one does not. It seems as if the app does not even go into the dispatch_async method.

EDIT: So basically all I need to do is tell the server that a user has force quit the app, while that user was signed in. How could I do this?

Any ideas?


Solution

  • applicationWillTerminate is the last method that get called before app is being terminated!! So, you can't do anything after that, if you want to perform something in background then begin that task when you performing your operation, you can't begin background task from applicationWillTerminate because your app will not be in background after this method call!!