2015-03-03 77 views
0

即使我的應用程序在後臺運行,我也想繼續在後臺執行特定的任務。保持NSTimer運行甚至應用程序在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"); 
} 
+1

嘿,這篇文章似乎是你的問題的解決方案。 http://stackoverflow.com/questions/12916633/how-to-run-the-timer-in-background-of-the-application – LoVo 2015-03-03 10:20:57

+0

@LoVo你解決了我的問題。謝謝.. – Rakesh 2015-03-03 10:33:43

+0

@Rakesh不,它不會。看看這種方法的應用程序文檔。 https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIApplication_Class/#//apple_ref/occ/instm/UIApplication/beginBackgroundTaskWithExpirationHandler: 你在做什麼是反對蘋果推薦,這贏了即使工作超過幾分鐘 – KIDdAe 2015-03-03 13:29:04

回答

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

} 

我認爲它對你的幫助

+0

這應該用於告訴iOS,在進入睡眠模式之前,您需要完成一些事情。 Cf Apple doc'您不應該使用這種方法,只是爲了讓您的應用程序在移動到後臺後繼續運行。「# 最重要的是,這種方法在很長一段時間內不會工作。 – KIDdAe 2015-03-03 13:27:09

2

你不能在後臺有一個計時器。它可能會工作很短的時間,但如果您沒有註冊後臺模式,您的應用程序將很快進入睡眠模式。

可用的模式可能是:

  • 音頻
  • 位置更新
  • 背景取
  • 其他...

看看Background execution documentation更多信息