0

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");
}
Rakesh
  • 1,177
  • 1
  • 15
  • 31
  • 1
    Hey, this post seems to be the solution for your problem. http://stackoverflow.com/questions/12916633/how-to-run-the-timer-in-background-of-the-application – LoVo Mar 03 '15 at 10:20
  • @Rakesh No it won't. Take a look at the the App Doc of this method. https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIApplication_Class/#//apple_ref/occ/instm/UIApplication/beginBackgroundTaskWithExpirationHandler: What you're doing is against Apple recommandation, and this won't even work more than a few minutes – KIDdAe Mar 03 '15 at 13:29

2 Answers2

2

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

KIDdAe
  • 2,714
  • 2
  • 22
  • 29
-2
- (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

Ravi Gautam
  • 960
  • 2
  • 9
  • 20
saravanaa
  • 9
  • 9
  • This should be use to tell iOS that you need to finish something before going in sleep mode. Cf Apple doc `You should not use this method simply to keep your app running after it moves to the background.` And most important, this won't work for a long duration. – KIDdAe Mar 03 '15 at 13:27