[英]How to Run Timer if the App goes to Background?
I try to run a Function in SceneDelegate.swift if the App goes to Background.如果应用程序进入后台,我会尝试在 SceneDelegate.swift 中运行一个函数。
if the App entering the Background the Timer Stops.如果应用程序进入后台计时器停止。 if have added the Background Modes and select the Background Processing.如果添加了后台模式并选择后台处理。
but timer stops everytime!但计时器每次都会停止!
func runtimerAction(){
Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in
print("Timer fired!")
}
}
func sceneDidEnterBackground(_ scene: UIScene) {
runtimerAction()
(UIApplication.shared.delegate as? AppDelegate)?.saveContext()
}
As per Apple's restrictions your app need background mode to do anything in background and even then you still can't run a timer on background.根据 Apple 的限制,您的应用程序需要后台模式才能在后台执行任何操作,即使如此,您仍然无法在后台运行计时器。
If you need a counter to check how much time has passed since X can save the time (IE: Date()
) and then check against the saved time to see how much time has passed since app last went to background.如果您需要一个计数器来检查自 X 可以保存时间以来已经过去了多少时间(即: Date()
),然后检查保存的时间以查看自应用程序上次进入后台以来已经过去了多少时间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.