2015-02-23 46 views
0

我正在使用beginBackgroundTaskWithExpirationHandler方法在applicationDidEnterBackground委託方法中保持NSTimer繼續運行。但是如果長時間在後臺留下(在我的情況下7-10分鐘),應用程序會在很長一段時間後死亡。我不希望我的應用程序被殺,並且我希望計時器在後臺運行。我該如何擺脫這個問題。以下是我寫的applicationDidEnterBackground方法應用程序如果使用beginBackgroundTaskWithExpirationHandler IOS

- (void)applicationDidEnterBackground:(UIApplication *)application { 
    if ([application respondsToSelector:@selector(setKeepAliveTimeout:handler:)]) { 
     [application setKeepAliveTimeout:600 handler:^{ 

      DDLogVerbose(@"KeepAliveHandler"); 

      // Do other keep alive stuff here. 
     }]; 
    } 

    /* 
    * The following code is used to make the app running in background state as certain features 
    * (eg: NSTimer) doesn not run if its in background or if the phone is locked 
    */ 
    UIBackgroundTaskIdentifier locationUpdater =[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{ 
     [[UIApplication sharedApplication] endBackgroundTask:locationUpdater]; 
    } ]; 

} 

回答

2

beginBackgroundTaskWithExpirationHandler代碼只是爲了讓你完成幾分鐘有限長度任務應用前景離開後。相當有意的是,iOS除了非常狹窄的情況(例如VOIP,音頻應用程序,導航應用程序)或窄功能需求(重大更改位置服務,後臺提取等)之外不會讓您的應用程序永遠在後臺運行。但是你不能只在後臺運行任意代碼。

有關這些選項的討論,請參閱適用於iOS的應用程序編程指南中的Background Execution部分。

+0

那麼如何解決這個問題呢? – user1512727 2015-02-23 13:16:02

+1

如果你描述你想要做的事情,我們可能會提供替代品,但是,一般來說,iOS不允許任意應用程序繼續在後臺運行。 – Rob 2015-02-23 13:51:55

相關問題