Search code examples
iosiphonebackgroundnstimer

Keep NSTimer running even application goes in background in ios


I want to perform particular task in background continuously even my application goes in background.

Here is the code which i tried. Timer is firing only once when it enters in background.

- (void)applicationDidEnterBackground:(UIApplication *)application
    {
      NSTimer * timer = [NSTimer timerWithTimeInterval:2.0
                                    target:self
                                  selector:@selector(timerTicked)
                                  userInfo:nil
                                   repeats:YES];
            [[NSRunLoop mainRunLoop] addTimer:timer
                                      forMode:NSDefaultRunLoopMode];
    }

- (void) timerTicked 
{
    NSLog(@"Timer method");
}

Solution

  • - (void)applicationDidEnterBackground:(UIApplication *)application {
    
        UIBackgroundTaskIdentifier bgTask = UIBackgroundTaskInvalid;
        bgTask = [[UIApplication sharedApplication]
                  beginBackgroundTaskWithExpirationHandler:^{
                      [[UIApplication sharedApplication] endBackgroundTask:bgTask];
                  }];
    
       // NotificationTimer  its timer
       // myMethod1 call ur method 
    
        NotificationTimer = [NSTimer scheduledTimerWithTimeInterval: Interval
                                         target: self
                                       selector:@selector(myMethod1)
                                       userInfo: nil repeats:YES];
    
    }
    

    I think its help to u