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

查看:41
本文介绍了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?

这是我想要发生的事情:

here's what i want to happen:

运行应用程序 -> 等待 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天全站免登陆