UIBackgroundTaskIdentifier is not working relaunching after its expires

592 Views Asked by At

I have a app that fetch some content from server via REST api after every 5 mins in background using the UIBackgroundTaskIdentifier. My problem is that this works fine for 1,2 hours and then after it is expired it never re starts the background task. The code I am using is given below,

In AppDelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{
          UIApplication* app = [UIApplication sharedApplication];

            self.expirationHandler = ^{
                [app endBackgroundTask:self.bgTask];
                self.bgTask = UIBackgroundTaskInvalid;
        //      self.bgTask = [app beginBackgroundTaskWithExpirationHandler:expirationHandler];
                NSLog(@"Expired");
                self.jobExpired = YES;
                while(self.jobExpired) {
                    // spin while we wait for the task to actually end.
                    [NSThread sleepForTimeInterval:1];
                }
                self.bgTask = [app beginBackgroundTaskWithExpirationHandler:expirationHandler];
                // Restart the background task so we can run forever.
                [self startBackgroundTask];
            };
            self.bgTask = [app beginBackgroundTaskWithExpirationHandler:expirationHandler];

            [self monitorBatteryStateInBackground];
    }

    - (void)monitorBatteryStateInBackground
    {
        NSLog(@"Monitoring update");
        self.background = YES;
        [self startBackgroundTask];
    }

    - (void)startBackgroundTask
    {
        NSLog(@"Restarting task");
        // Start the long-running task.
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            // When the job expires it still keeps running since we never exited it. Thus have the expiration handler
            // set a flag that the job expired and use that to exit the while loop and end the task.
            while(self.background && !self.jobExpired)
            {
                [self uploadPhotostoServer];
                [NSThread sleepForTimeInterval:240.0];
            }

            self.jobExpired = NO;
        });
    }

In expired section it do come but never calls the method [self startBackgroundTask]

Any help will be much appreciated.

0

There are 0 best solutions below