Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSTimer stops firing in Background after some time

Tags:

ios

timer

nstimer

Hey I am developing an app in which i have to make API call every 30 sec, so i created NSTimer for it. But when my app goes into background timer stops firing after 3-4 minutes. So it works only 3-4 minutes in background,but not after that. How can i modify my code so that timer would not stop.

Here is some of my code.

- (IBAction)didTapStart:(id)sender {
    NSLog(@"hey i m in the timer ..%@",[NSDate date]);
    [objTimer invalidate];
    objTimer=nil;

    UIBackgroundTaskIdentifier bgTask = UIBackgroundTaskInvalid;
    UIApplication  *app = [UIApplication sharedApplication];
    bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
        [app endBackgroundTask:bgTask];
    }];
    objTimer = [NSTimer scheduledTimerWithTimeInterval:30.0 target:self
                                                       selector:@selector(methodFromTimer) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:objTimer forMode:UITrackingRunLoopMode];
}

-(void)methodFromTimer{
    [LOG debug:@"ViewController.m ::methodFromTimer " Message:[NSString stringWithFormat:@"hey i m from timer ....%@",[NSDate date] ]];
    NSLog(@"hey i m from timer ....%@",[NSDate date]);
}

I even changed the code with the following:

[[NSRunLoop mainRunLoop] addTimer:objTimer forMode:NSRunLoopCommonModes];

This didn't work either.

like image 384
Vivek Shah Avatar asked Dec 09 '22 06:12

Vivek Shah


1 Answers

Don't create UIBackgroundTaskIdentifier task as local and make it global as below:

Step -1

Initiating varible

Step -2

ViewDidLoad Method and added barButton

Step -3

BarButton method call

Step -4

Timer method call

As local one loose scope and global one won't ,and I created a demo and ran it for sometime with 1 sec repeating timer ,and worked smooth. Still if u face issue pls let me know.

I ran again demo and here are logs of it running. enter image description here

So its working fine and more than 3 minutes. Also that 3 minute logic is right but as uibackgroundtask is initiated so it shouldn't let it kill this task of timer.

Edited Part:- bgTask = [app beginBackgroundTaskWithExpirationHandler:^{ [app endBackgroundTask:bgTask]; //Remove this line and it will run as long as timer is running and when app is killed then automatically all vairbles and scopes of it are dumped. }];

Check it and let me know if it works out or not.

Hey I run ur code and I reached the expirationHandler but after released debug point ,the timer was running smooth.

Highlighted part is when I reached handler

like image 134
nikhil84 Avatar answered Dec 11 '22 10:12

nikhil84