Swift 3-如何使计时器在后台工作 [英] Swift 3 - How to make timer work in background

查看:161
本文介绍了Swift 3-如何使计时器在后台工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试开发一个可以使计时器在后台运行的应用程序.

i am trying to do an application which can make a timer run in background.

这是我的代码:

let taskManager = Timer.scheduledTimer(timeInterval: 10, target: self, selector: #selector(self.scheduleNotification), userInfo: nil, repeats: true)
        RunLoop.main.add(taskManager, forMode: RunLoopMode.commonModes)

上面的代码将执行将调用本地通知的功能. 该应用程序在前台运行时有效,我如何使其在后台运行?

above code will perform a function that will invoke a local notification. this works when the app is in foreground, how can i make it work in the background?

我试图放置多条打印线,但我发现当我最小化(按下主屏幕按钮)应用程序时,计时器停止运行,当我返回到应用程序时,计时器恢复运行.

i tried to put several print lines and i saw that when i minimize (pressed the home button) the app, the timer stops, when i go back to the app, it resumes.

我希望计时器仍在后台运行.有办法吗?

i wanted the timer to still run in the background. is there a way to do it?

这是我想发生的事情:

运行应用程序->等待10秒->收到通知->等待10秒->收到通知->然后返回等待并再次接收

run app -> wait 10 secs -> notification received -> wait 10 secs -> notification received -> and back to wait and received again

发生在前台时.但不在背景中.请帮忙.

that happens when in foreground. but not in background. pls help.

推荐答案

,您可以转到功能"并打开背景模式和活动的音频. AirPlay以及图片和图片.

you can go to Capabilities and turn on background mode and active Audio. AirPlay, and picture and picture.

这确实有效.您不需要设置DispatchQueue. 您可以使用计时器.

It really works . you don't need to set DispatchQueue . you can use of Timer.

Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { (t) in

   print("time")
}

这篇关于Swift 3-如何使计时器在后台工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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