如何无限地每 1 分钟 运行 一个 iOS 应用程序?

How to run an iOS application every 1 minute infinitely?

我制作了一个应用程序,需要每 1 分钟向服务器发送一次位置和状态更新。 我尝试了以下方法,但其中 none 帮助了我。有解决办法吗?

1 - NSTimer - 许多人建议这样做。但问题出在 backgroundMode 上,它只能工作 20 分钟。在该应用程序停止发送数据之后。

2 - BackgroundFetchMode - 一开始看起来是正确的解决方案。但是这个能力不保证每1分钟运行申请一次。它有一个算法 iOS 决定哪个应用程序应该 运行.

This API is not like a timer task, system will decide when to call the handler depending on many constraints.so if you set timeInterval to 2.00f(2secs), handler is called for every 2+(minimum) secs.

3 - LocationUpdate - 这种方式同样行不通,因为如果你移动至少 500 米,它只会 运行 你的应用程序。

Apps can expect a notification as soon as the device moves 500 meters or more from its previous notification. It should not expect notifications more frequently than once every five minutes. If the device is able to retrieve data from the network, the location manager is much more likely to deliver notifications in a timely manner.

4 - Push Notifications - 在一篇文章中说用这种方法你可以 运行 在定义的时间内申请,它确实做到了!

您可以在定义的计划时间内安排通知。但问题是向用户显示通知。我需要在后台静音。

此外,您不能每 1 分钟 运行 一些代码。它只是向用户显示通知。用户应该点击你的通知然后 didReceiveLocalNotification 可用,您可以 运行 代码。

正如 Apple 在其 documentation 中所述:

In iOS, only specific app types are allowed to run in the background:

  • Apps that play audible content to the user while in the background, such as a music player app
  • Apps that record audio content while in the background
  • Apps that keep users informed of their location at all times, such as a navigation app
  • Apps that support Voice over Internet Protocol (VoIP)
  • Apps that need to download and process new content regularly
  • Apps that receive regular updates from external accessories

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.

您可以在 link 中阅读有关实施和声明这些后台任务的所有内容。但是,如果你的是其他类型的App,或者你不能使用系统框架,你的App是没办法一直在后台运行的。即使是这样,您也应该始终期望系统出于某种原因停止您的任务(f.e。重新启动 phone)。