简体   繁体   English

即使应用程序在ios中进入后台,也可以保持NSTimer运行

[英]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 我认为这对你有帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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