应用程序终止时执行后台任务 [英] Perform background tasks when app is terminated

查看:121
本文介绍了应用程序终止时执行后台任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的学校创建一个应用程序,如果网站上有新标记,应该每n分钟检查一次。
要在用户首次登录时执行此操作,实际标记的编号将保存在UserDefaults中。当应用程序终止时,在n分钟后,将重新计算标记数并与之前的标记进行比较,并在数字发生更改时发送通知。

I'm creating an application for my school which should check every n minutes if there is a new mark on the website. To do this when the user login for the first time, the number of the actual mark is saved in the "UserDefaults". When app is terminated, after n minutes, the number of mark is recounted and compared with the previous one and send a notification in case the number is changed.

我是什么我想知道是否有办法执行这项任务。我试图在-applicationWillTerminate中创建一个计时器 - 但它只被触发一次。
这是我试过的:

What I'd like to know if there is a way to perform this task. I've tried to create a timer in -applicationWillTerminate- but it's fired only once. This is what I tried:

func applicationWillTerminate(_ application: UIApplication) {
    DispatchQueue.main.async {
        self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(AppDelegate.findMark), userInfo: nil, repeats: true)
        self.timer.fire()
    }
}

选择器findMark是任务。

Selector findMark is the task.

提前致谢!

推荐答案

您有两种选择


  1. 后台应用刷新

  2. 无声推送通知

最简单的一个是后台应用刷新。因为以后需要服务器才能发送通知。您可以查看以下 API 以了解相关用途。基本上,您在应用的功能/背景模式上设置后台提取功能。然后,iOS会不时唤醒您的应用并调用应用程序(_:performFetchWithCompletionHandler:)委托。您将有大约30-45秒来调用您的函数并调用完成处理程序。如果您没有按时完成,iOS将会终止您的应用。如果您不遵守规则,iOS将减少唤醒的机会。有关背景模式的更详细用法,您可以查看以下教程

Easiest one is Background App Refresh. Because later one needs a server to send the notification. You can check following API for the usage. Basically you set Background Fetch capability on Capabilities/Background Modes of your app. Then from time to time, iOS will wake up your app and call application(_:performFetchWithCompletionHandler:) delegate. You will have around 30-45 seconds to call your function and call completion handler. If you don't finish it on time, iOS will kill your app. If you don't obey the rules, iOS will give you less chances to wake up. For more detailed usage of Background Modes, you may check following tutorial

这篇关于应用程序终止时执行后台任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆