iOS在后台的代码中运行计时器 [英] iOS Running a timer within your code in the background

查看:337
本文介绍了iOS在后台的代码中运行计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此我读到在iOS中,当您的应用在后台运行时,所有计时器都会暂停.我还读到您可以使用beginBackgroundTaskWithExpirationHandler(像这样)在bg中运行任务.

So I've read that in iOS, all timers will pause when your app is running in the background. I've also read that you can run tasks in the bg using beginBackgroundTaskWithExpirationHandler (like so).

我要实现的目标是每3分钟调用一次方法,而在第一个方法之前的固定时间调用另一个方法.我设法在一个NSTimer中执行了此操作,然后以一种允许我执行此操作的方式重复执行.它可以正常运行,但是当应用程序在后台运行时显然被禁用(或暂停)-我只能基于上述原因进行推测.

What I am trying to achieve is to call a method once every 3 minutes, and another method a fixed-amount of time before the first one. I have managed to do this within one NSTimer which repeats in a way that lets me do this. It works fine but is obviously disabled (or paused) when the app is in the background - I can only assume because of the reason described above.

有人知道有没有一种方法可以运行计时器或至少在特定时间后调用某些东西,以便我可以做到这一点?

Does anyone know if there's a way to run a timer or at least call something after a specific amount of time so I can do this?

推荐答案

基本上,如果要继续在后台运行,则必须满足以下要求之一.来自Apple文档:

Basically if you want to continue running active in the background you have to meet one of the following requirements. From the Apple docs:

执行长期运行的后台任务

对于需要更多执行时间才能实现的任务,您必须 请求特定权限以在后台运行它们而无需 他们被停职了.在iOS中,仅允许特定的应用类型 在后台运行:

For tasks that require more execution time to implement, you must request specific permissions to run them in the background without their being suspended. In iOS, only specific app types are allowed to run in the background:

  • 在后台播放可听内容的应用程序,例如音乐播放器应用程序
  • 始终使用户知道其位置的应用程序,例如导航应用程序
  • 支持互联网协议语音(VoIP)的应用
  • 需要下载和处理新内容的书报摊应用程序
  • 从外部附件接收定期更新的应用
  • Apps that play audible content to the user while in the background, such as a music player app
  • Apps that keep users informed of their location at all times, such as a navigation app
  • Apps that support Voice over Internet Protocol (VoIP)
  • Newsstand apps that need to download and process new content
  • 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.

http://developer.apple.com/library/ios/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/ManagingYourApplicationsFlow/ManagingYourApplicationsFlow.html#//apple_ref/doc/uid/TP40007072-CH4-SW24

这篇关于iOS在后台的代码中运行计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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