app delegate 中 performFetchWithCompletionHandler 的用途是什么?

what is the use of performFetchWithCompletionHandler in app delegate?

我对 performFetchWithcompletionHandler 如何参与 iOS 应用程序生命周期感到有点困惑。在文档中提到它给了我们 30 秒的时间来下载任何数据,但是我们的应用程序会在那时冻结 30 秒吗?

这与后台获取有关,例如当应用收到静默通知时。在这种情况下,iOS 在后台唤醒应用程序最多 30 秒。并按照编写器代码执行操作并终止应用程序。所以用户不会意识到这一点。

不建议在该方法中编写复杂的逻辑performFetchWithcompletionHandler。原因是时间限制(30 秒),应用程序开发人员无法控制它。

要完成这项工作,应在项目的 capabilities 中启用 background mode

关于此的示例之一是静默推送通知(通知负载具有密钥 content-available = 1

更多详情see this

... will our app freeze for 30 seconds at that time?

不,恰恰相反。当您的应用程序暂停时会调用此方法,但 OS 将让您检查要检索的数据。因此,您的应用程序将在后台 运行 被唤醒,并且将调用此方法,此时您可以执行快速提取(不超过 30 秒)以查看是否有任何数据要检索。处理完快速提取后,调用完成处理程序让 OS 知道您已完成处理,您的应用程序可以再次安全地挂起。

但是,如果您未能在 30 秒内完成您的请求,您的应用可能会被立即终止,并且不会参与未来的后台提取。所以在规定的时间内完成很重要。


正如the docs所说:

Implement this method if your app supports the fetch background mode. When an opportunity arises to download data, the system calls this method to give your app a chance to download any data it needs. Your implementation of this method should download the data, prepare that data for use, and call the block in the completionHandler parameter.

When this method is called, your app has up to 30 seconds of wall-clock time to perform the download operation and call the specified completion handler block. In practice, your app should call the completion handler block as soon as possible after downloading the needed data. If you do not call the completion handler in time, your app is terminated. More importantly, the system uses the elapsed time to calculate power usage and data costs for your app’s background downloads. If your app takes a long time to call the completion handler, it may be given fewer future opportunities to fetch data in the future. For more information about supporting background fetch operations, see Background Execution in App Programming Guide for iOS.