苹果允许后台任务运行多久?

我必须上传一个图像文件数据库,因此,我偶然发现苹果的后台执行指南 ,以确保应用程序仍然上传数据时,用户暂停或终止我的应用程序。

但是在说明中,如果我们调用beginBackgroundTaskWithName:expirationHandler:beginBackgroundTaskWithExpirationHandler:来启动一个后台任务,它会说giving it a little extra time to finish its work

多lesslittle extra time精确?

纠正我,如果我错了,但我偶然发现了 Xamarin讨论iOS背景function的完美文章 。

我将简单地分解成两个部分,ios 7和ios 7+:

iOS版本的前7

答案只是600秒(10分钟),理由是由上面的文章提供的。

iOS版本7+

答案是时间系统分配你是机会主义的。 你将不得不使用@Gary财富的build议

 NSLog(@"Time Remaining: %f", [[UIApplication sharedApplication] backgroundTimeRemaining]); 

找出。 机会主义的原因是iOS 7+处理后台任务的方式是完全不同的,当然是优化的。 确切地说,它有一个间歇的行为,因此,如果你需要后台任务,比如下载大量的数据,那么使用NSURLSession代替它会更加有效。

但是,在我的特殊情况下,我正在上传一个包含一个文件的单个对象。 我不必考虑NSURLSession上传less量的数据。 此外,它的上传任务,它可以花费尽可能多的时间,因为它想要的。 🙂

对于这些TL;DR访问者,上面的答案应该是足够的。 有关更多详细信息,请参阅上面的文章。

如果您想在应用程序处于后台时上传文件,则应使用Apple的后台服务。 iOS会给你的应用程序的时间约。 3分钟(根据一些经验)完成你的任务,然后它会杀了你的应用程序。

苹果允许在特殊情况下运行更长的应用程序。 为此,您需要在您的info.plist文件中使用UIBackgroundModes。 有关这些特殊情况的更多信息,请参阅此链接上的表3-1。

编辑
这篇文章描述了后台任务运行时间以及如何在iOS中实现长时间运行的后台任务。
https://gooddevbaddev.wordpress.com/2013/10/22/ios-7-running-location-based-apps-in-the-background/

时间量将根据许多不同的variables而有所不同,但可以通过引用UIApplication上的backgroundTimeRemaining属性来检查该值:

 NSLog(@"Time Remaining: %f", [[UIApplication sharedApplication] backgroundTimeRemaining]); 

在理论上,你有5秒钟的时间来closures你想在后台执行的任务,如果你不这样做,你的应用程序可能会被杀死。

之后,你可以调用'beginBackgroundTaskWithExpirationHandler',你必须做好准备,以防万一苹果提供的“额外的时间”不足以完成你需要完成的任务。

编辑:

当iOS应用程序进入后台时,冗长的任务是否暂停? :

从iOS应用程序编程指南:

 Your app delegate's applicationDidEnterBackground: method has approximately 5 seconds to finish any tasks and return. In practice, this method should return as quickly as possible. If the method does not return before time runs out, your app is killed and purged from memory. If you still need more time to perform tasks, call the beginBackgroundTaskWithExpirationHandler: method to request background execution time and then start any long-running tasks in a secondary thread. Regardless of whether you start any background tasks, the applicationDidEnterBackground: method must still exit within 5 seconds. 

来自Raywenderlich:“再次,没有保证,API文档甚至没有提供球场号码 – 所以不要依赖这个数字。 你可能会得到5分钟或5秒,所以你的应用程序需要准备任何东西!':

http://www.raywenderlich.com/29948/backgrounding-for-ios

您的应用程序获取后台后获得多less时间取决于iOS。 您授予的时间没有保证,但您始终可以检查UIApplication的backgroundTimeRemaining属性。 这会告诉你你离开了多less时间。 一般而言,观察为基础的共识是,通常你会得到10分钟。 再次,没有保证,API文档甚至没有提供球场号码 – 所以不要依赖这个数字。 你可能会得到5分钟或5秒,所以你的应用程序需要为任何事情做好准备!