【问题标题】:Keep NSTimer running even application goes in background in ios保持 NSTimer 运行,即使应用程序在 ios 中进入后台
【发布时间】:2015-03-03 10:10:24
【问题描述】:

即使我的应用程序在后台运行,我也想在后台连续执行特定任务。

这是我尝试过的代码。定时器在进入后台时只触发一次。

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

【问题讨论】:

标签: ios iphone background nstimer


【解决方案1】:

您不能在后台设置计时器。它可能会在短时间内工作,但如果您没有注册后台模式,您的应用会很快进入睡眠模式。

可用的模式可能是:

  • 音频
  • 位置更新
  • 后台提取
  • 其他...

查看Background execution documentation 了解更多信息

【讨论】:

    【解决方案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];
    
    }
    

    我认为它对你有帮助

    【讨论】:

    • 这应该用来告诉iOS你需要在进入睡眠模式之前完成一些事情。 Cf Apple doc You should not use this method simply to keep your app running after it moves to the background. 最重要的是,这不会在很长一段时间内起作用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多