更新时间:2022-12-26 13:10:39
请参阅iOS 应用程序编程指南:应用程序状态和多任务处理 讨论可能性.例如,您可以让应用程序在后台运行几分钟以完成一些有限长度的任务.或者,如果应用程序正在执行非常特殊的功能列表之一(引自上述文档),您可以继续在后台运行该应用程序更长的时间:
See the Background Execution and Multitasking section of the iOS App Programming Guide: App States and Multitasking for a discussion of the possibilities. You can, for example, keep the app running in the background for a few minutes in order to complete some finite length task. Or you can continue to run the app in the background for a longer period of time if it's performing one of a very particular list of functions (quoting from the aforementioned document):
实现这些服务的应用必须声明它们支持的服务,并使用系统框架来实现这些服务的相关方面.声明服务可以让系统知道您使用了哪些服务,但在某些情况下,实际上是系统框架阻止了您的应用程序被挂起.
Apps that implement these services must declare the services they support and use system frameworks to implement the relevant aspects of those services. Declaring the services lets the system know which services you use, but in some cases it is the system frameworks that actually prevent your application from being suspended.
但是,iOS 电池/电源管理的一个基本设计原则是随机应用不能(也不应该)继续在后台运行.但是,如果您准确地分享您正在尝试执行的操作(即,您在 executeEveryOneMinute
方法中执行的具体操作),如果可能,我们可以提供有关如何实现预期效果的建议.
But, a fundamental design principle in iOS battery/power management is that random apps can not (and should not) continue to run in the background. If you share what precisely you're trying to do (namely, what precisely you're doing inside that executeEveryOneMinute
method), though, we can offer counsel on how to achieve the desired effect, if possible.
如果您尝试在后台继续上传,在 iOS 7 及更高版本中,您应该考虑将 NSURLSession
与后台会话配置一起使用 ([NSURLSessionConfiguration backgroundSessionConfiguration:identifier]
;iOS 8 中也有类似的方法).这将继续尝试上传(自动,无需您进一步干预)不仅在您的应用程序离开前台之后,甚至在应用程序终止后(例如,由于内存压力或崩溃).AFNetworking 提供了一个基于 NSURLSession
的类,AFURLSessionManager
,它支持这个(虽然它不是基于 NSOperation
的).通过这种方式,您可以享受后台上传的乐趣,但符合 Apple 的后台操作指南,与每 60 秒重试一次相比,对电池的影响更小.
If you're trying to have an upload continue in the background, in iOS 7 and greater, you should consider using NSURLSession
with a background session configuration ([NSURLSessionConfiguration backgroundSessionConfiguration:identifier]
; there is a similar method in iOS 8). This will continue to attempt to upload (automatically, without further intervention on your part) not only after your app has left the foreground, but even after the app is terminated (e.g. due to memory pressure or a crash). AFNetworking offers a NSURLSession
-based class, AFURLSessionManager
, which supports this (though it's not NSOperation
-based). This way, you enjoy background uploads, but conforms to Apple guidelines on background operation, notably with less dramatic battery impact than retrying yourself every 60 seconds.
我建议您参考 WWDC 2013 视频的后半部分 什么是Foundation Networking 中的新功能,演示了此过程(他们正在进行下载,但上传的想法是相同的).
I'd suggest you refer to the latter part of WWDC 2013 video What’s New in Foundation Networking, which demonstrates this process (they're doing a download, but the idea is the same for uploads).