pt850运行下载界面_利用后台执行功能pt 2

pt850运行下载界面

How to effectively distribute and defer work from the foreground to the background.

如何有效地分配工作并将工作从前台推迟到后台。

Previously, we had a good overview of how the Background Execution is handled after iOS 13. Now is time to get our hands on it. In this article I will share with you my own implementation and my findings.

以前 ,我们对iOS 13之后如何处理后台执行进行了很好的概述。现在是时候开始实践了。 在本文中,我将与您分享我自己的实现和我的发现。

I have set up an app to demonstrate how the background tasks works in practice. It follows Apple’s Project Sample (you can find here), but it is a bit simpler. It is called Footprints.

我已经建立了一个应用程序来演示后台任务如何在实践中工作。 它遵循Apple的Project Sample(您可以在此处找到),但是它有点简单。 这就是所谓的足迹

It mainly schedules 2 tasks (one of each type) when the app goes into the background and when the task is performed, it records in a local storage the time of execution and the task nature.

当应用程序进入后台并且执行任务时,它主要计划2个任务(每种类型之一),它在本地存储中记录执行时间和任务性质。

My goal was to show when the system was opening my app to perform what task. Let me walk you through it step by step:

我的目标是显示系统何时打开我的应用程序以执行什么任务。 让我一步一步地指导您:

入门 (Getting started)

There are some configuration to be set in order to add tasks to the Background Scheduler. Apple has a great documentation for that with helpful resources (which you can check here). Overall, you must:

为了将任务添加到后台计划程序,需要设置一些配置。 Apple拥有出色的文档,其中包含有用的资源(您可以在此处查看 )。 总体而言,您必须:

  • In your Xcode, under the Project Settings “Signing & Capabilities” Tab, add a Background Mode Capability;

    在您的Xcode中,在“项目设置”的“签名和功能”选项卡下,添加背景模式功能;

  • Tick the Background Fetch and/or Background Processing box;

    勾选“ 后台获取”和/或“ 后台处理”框;

  • Add this key to your Info.plist: BGTaskSchedulerPermittedIdentifiers. It is a list of Strings. You should append all your Background Task Identifiers on it;

    将此密钥添加到您的Info.plistBGTaskSchedulerPermittedIdentifiers 。 它是一个字符串列表。 您应该在其上附加所有后台任务标识符。

注册后台任务 (Registering Background Tasks)

Once these steps are done, you can then register the identifiers in the BGTaskScheduler using func register(forTaskWithIdentifier: String, using: DispatchQueue?, launchHandler: (BGTask) -> Void) -> Bool. Preferable, do it when your app is about to finish launching.

完成这些步骤后,您可以使用func register(forTaskWithIdentifier: String, using: DispatchQueue?, launchHandler: (BGTask) -> Void) -> BoolBGTaskScheduler注册标识符。 最好在您的应用即将完成启动时执行此操作。

func registerBackgroundTask() {
  BGTaskScheduler.shared.register(forTaskWithIdentifier: "YOUR_TASK_IDENTIFIER", using: nil) { task in
    // Execute your background task (This handler will be used upon launch) ...
  }
}

Now you can schedule the background task whenever you find suitable.

现在,您可以在合适的时候安排后台任务。

When the system is ready to perform your task in the background, it will wake up your app and put it in the background state. If it was previously terminated, it will launch it first and then immediately put in the background. Otherwise, it will transition from the suspended state to the background.

当系统准备好在后台执行任务时,它将唤醒您的应用程序并将其置于后台状态。 如果它先前已终止,它将先启动它,然后立即放在后台。 否则,它将从暂停状态过渡到后台。

安排后台任务 (Scheduling Background Tasks)

In order to schedule background tasks, we need to submit requests to the BGTaskScheduler. These requests will hold the conditions specification to run our task.

为了安排后台任务,我们需要向BGTaskScheduler提交请求。 这些请求将包含条件规范以运行我们的任务。

To schedule an App Refresh Task, you will need to submit a BGAppRefreshTaskRequest. Optionally, it allows you to determine a start time to run the task.

要安排应用刷新任务,您需要提交BGAppRefreshTaskRequest 。 (可选)它允许您确定运行任务的开始时间。

func scheduleAppRefreshTask() {
  // Creates BGAppRefreshTaskRequest
  let request = BGAppRefreshTaskRequest(identifier: "YOUR_BGTASK_IDENTIFIER")
  // Optionally, we can set a start date to run the task
  request.earliestBeginDate = Date(timeIntervalSinceNow: 15 * 60) // Fetch no earlier than 15 minutes from now

  do {
    // Submit request to the Scheduler
    try BGTaskScheduler.shared.submit(request)
    print("✅ BGAppRefreshTaskRequest successfully scheduled")
  } catch let error {
    print("😬 Could not schedule BGAppRefreshTaskRequest: \(error)")
  }
}

For Processing Tasks, submit a BGProcessingTaskRequest instead. You will be able to determine if the task requires external power and network connectivity.

对于处理任务,请提交BGProcessingTaskRequest 。 您将能够确定任务是否需要外部电源和网络连接。

func scheduleProcessingTask() {
  // Create BGProcessingTaskRequest
  let request = BGProcessingTaskRequest(identifier: BGTaskIdentifier.processing)
  // If true, the task will be executed only if the device has connectivity
  request.requiresNetworkConnectivity = true
  // If true, the task will be executed only if the device is recharging
  request.requiresExternalPower = true


  do {
    // Submit request to the Scheduler
    try BGTaskScheduler.shared.submit(request)
    print("✅ BGProcessingTaskRequest successfully scheduled")
  } catch let error {
    print("😬 Could not schedule BGProcessingTaskRequest: \(error)")
  }
}

测试后台任务 (Testing Background Tasks)

We don’t control how or when the Background Scheduler launches our tasks. In fact, it is arbitrarily. This is because the Scheduler will prioritise saving energy.

我们不控制后台调度程序启动任务的方式或时间。 实际上,它是任意的。 这是因为调度程序将优先考虑节能。

It is possible, though, to simulate the launch and expiration of a background task by running in the debug console the following instructions:

但是,可以通过在调试控制台中运行以下指令来模拟后台任务的启动和到期:

e -l objc -- (void)[[BGTaskScheduler sharedScheduler] _simulateLaunchForTaskWithIdentifier:@“…”]e -l objc -- (void)[[BGTaskScheduler sharedScheduler] _simulateExpirationForTaskWithIdentifier:@“…”]

To do so, your app should be running in foreground and you need to have scheduled a task previously.

为此,您的应用程序应在前台运行,并且您需要事先安排任务。

结果 (Outcomes)

I’ve been checking this app every morning and by the evening. Accordingly to the Battery Life Software Team in Apple, the system will “learn” how you use the app and try to perform the App Refresh Tasks slightly before you actually open the app, so you can have the feeling of an always up-to-date app.

我每天早上和晚上都在检查此应用程序。 根据Apple的电池寿命软件团队的了解,该系统将在您真正打开应用程序之前“学习”您如何使用该应用程序并尝试执行“应用程序刷新任务”,因此您可以始终保持最新状态。日期应用程序。

In fact, that’s exactly what I’ve noticed. The system woke up my app roughly before the average hour I was used to open it (which turns to be in between my breakfast and lunch time).

实际上,这正是我所注意到的。 该系统大约在我用来打开应用程序的平均时间之前唤醒了我的应用程序(该时间介于我的早餐和午餐时间之间)。

On the other hand, with the Processing Task I’ve noticed it was running only by the night (even though I kept my app connected to the power the whole day long).

另一方面,通过“处理任务”,我注意到它仅在晚上运行(即使我整天都保持应用程序与电源连接)。

Although you may set that you don’t need external power, the system will likely prefer to execute the launch handlers when the device is recharging.

尽管您可能设置为不需要外部电源,但是系统可能会在设备充电时更喜欢执行启动处理程序。

结语 (Wrapping up)

We have reviewed some features and limitations of Background Tasks and behaviours of Background Execution. Below I’ve listed my main findings as well as my recommendations to you:

我们已经回顾了后台任务的某些功能和局限性以及后台执行的行为。 在下面,我列出了我的主要发现以及对您的建议:

  • Background execution is way more restricted scope than Foreground execution.

    后台执行比前景执行更受限制。
  • Your tasks will rely on the user’s circumstances to be launched.

    您的任务将取决于要启动的用户的情况。
  • Background Tasks are arbitrary. The system is optimised to reduce energy usage and increase device’s battery life. So we should not rely on the background to perform important work.

    后台任务是任意的。 该系统经过优化,可减少能耗并延长设备的电池寿命。 因此,我们不应依赖于背景来执行重要工作。
  • Do not schedule important business logic tasks in the background. You are not guaranteed when they will be run.

    不要在后台安排重要的业务逻辑任务。 您不能保证它们将在何时运行。
  • Do not schedule background tasks to be executed in a point far in the future.

    不要安排后台任务在将来的某个时间执行。
  • If you re-subscribe a task with the same identifier, it will override the previous schedule.

    如果您重新订阅具有相同标识符的任务,它将覆盖先前的计划。
  • Prevent your app to be terminated by the system while it is working on your background tasks. Set the task as completed if you finish earlier. This will keep your app in memory (suspended state) preventing it to be relaunched.

    防止应用程序在执行后台任务时被系统终止。 如果您较早完成,则将任务设置为已完成。 这会将您的应用保留在内存中(处于暂停状态),以防止重新启动该应用。
  • You have roughly 30 seconds to perform all your background tasks, not each one. Do not surpass this limit and balance it gracefully. Otherwise the system can stop launching your tasks.

    大约需要 30秒来执行所有后台任务,而不是每个。 不要超过此限制并保持平衡。 否则,系统将停止启动您的任务。

  • Processing tasks run only when the device is idle. The system terminates any background processing tasks running when the user starts using the device. Background refresh tasks are not affected.

    处理任务仅在设备空闲时运行。 当用户开始使用设备时,系统将终止正在运行的所有后台处理任务。 后台刷新任务不受影响。
  • Your development should be driven by the user experience. Think about your user first. Recognise your app isn’t the only one running.

    您的开发应受用户体验的驱动。 首先考虑您的用户。 认识到您的应用程序不是唯一运行的应用程序。

超越 (Going beyond)

Apple has a wide range of background execution APIs for all sorts of use cases you should definitely check out. You can find more information in Choosing Background Strategies for Your App.

Apple为您应该检查的各种用例提供​​了广泛的后台执行API。 您可以在为应用程序选择后台策略中找到更多信息。

Thanks for reading! I’m looking forward to know what problems we can solve with this! If you enjoyed this article and want to say the word, please contact me in twitter. Happy coding! 👨🏻‍💻

谢谢阅读! 我期待知道我们可以解决什么问题! 如果您喜欢这篇文章并想说这个词,请通过Twitter与我联系。 编码愉快! ‍💻

翻译自: https://medium.com/@felipericieri/leveraging-the-power-of-background-execution-pt-2-c637089dc28c

pt850运行下载界面

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值