简体   繁体   中英

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");
}

You can't have a timer in background. It may work for a short time but your app will quickly goes into sleep mode if you don't have a registered background mode.

Available modes may be :

  • Audio
  • Location updates
  • Background fetch
  • Others ...

Take a look at Background execution documentation for more info

- (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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM