簡體   English   中英

即使應用程序在ios中進入后台,也可以保持NSTimer運行

[英]Keep NSTimer running even application goes in background in ios

我想在后台連續執行特定任務,即使我的應用程序在后台運行。

這是我嘗試過的代碼。 計時器在進入后台時僅觸發一次。

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

您不能在后台使用計時器。 它可能會工作一小段時間,但是如果您沒有注冊的后台模式,您的應用將迅速進入睡眠模式。

可用的模式可能是:

  • 音訊
  • 位置更新
  • 后台獲取
  • 其他 ...

查看后台執行文檔以獲取更多信息

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

}

我認為這對你有幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM