2013-03-09 17 views
1

我知道我在拉吸管,但希望得到答案。iOS - 调度后台任务时NSTimer是否仍受Apple限制?

我有一个应用程序,需要在后台与服务器进行通信,无需用户干预。无论是推送通知到达还是至少定期(每5分钟左右)。

我可以潜在的螺栓固定位置更新并将其发送到服务器。我甚至可以证明使用粗略位置是正确的,所以苹果会批准它。最糟糕的情况是,我将为企业开发者许可证支付299美元,并使用本地分发(我唯一关心的分发版)。

我最后的希望是使用具有的NSTimer后台任务的定期调度。 使用此方法的应用程序是否仍然受Apple限制,允许使用后台任务的类型? (媒体/位置/ voip /报亭/外部设备)它似乎很歧视...

PS。该应用程序现在在ipod touch上以开发模式工作,包括与服务器的定期通信。至于背景模式,我还没有在plist中声明过任何东西。这是否意味着我没事?

回答

1

我已经实现了以下,并获得了苹果昨天批准的应用程序。我的应用程序不会做(媒体/位置/ VOIP /报摊/外部设备)

您可以通过使用利用的下面的代码在applicationDidEnterBackground获得600秒(10分钟)的最大时间:

if ([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)]) { //Check if our iOS version supports multitasking I.E iOS 4 
if ([[UIDevice currentDevice] isMultitaskingSupported]) { //Check if device supports mulitasking 
UIApplication *application = [UIApplication sharedApplication]; //Get the shared application instance 
__block UIBackgroundTaskIdentifier background_task; //Create a task object 
background_task = [application beginBackgroundTaskWithExpirationHandler:^{ 
    [application endBackgroundTask: background_task]; //Tell the system that we are done with the tasks 
    background_task = UIBackgroundTaskInvalid; //Set the task to be invalid 
    //System will be shutting down the app at any point in time now 
}]; 
//Background tasks require you to use asyncrous tasks 
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 
    //Perform your tasks that your application requires 
    NSLog(@"\n\nRunning in the background!\n\n"); 
    [application endBackgroundTask: background_task]; //End the task so the system knows that you are done with what you need to perform 
    background_task = UIBackgroundTaskInvalid; //Invalidate the background_task 
}); 
} 

} 

文档可以在这里找到http://disanji.net/iOS_Doc/#documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html

我刚刚实施的backgroundTaskIdentifier对象和无效background_task检查时,应用程序还活着,正在运行600秒。你甚至可以通过使用这个获得剩余时间

NSLog(@"Time remaining: %f", application.backgroundTimeRemaining); 
+0

我想我在网上看到了类似的代码。有人试图在接近过期时间的情况下调度另一个bg任务...不确定是否会启动应用程序。 – selytch 2013-03-09 06:13:26

+0

如果任务未在10分钟内结束(即600秒),则应用程序将自动终止。所以我在applicationWillTerminate中编写了代码来处理恢复选项,如果下载正在进行,如果下载量很少,我只需将其删除并将其设置为不可用。 – 2013-03-09 06:18:35

+0

只是放这个代码会保持你的应用程序活着,我正在单独的线程上做我的下载,并没有在此代码中添加任何东西。 – 2013-03-09 06:20:39