简体   繁体   English

如果应用程序进入后台,如何运行计时器?

[英]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.

相关问题 iOS 应用程序进入后台时运行的计时器 - Timer to run when iOS app goes to background 进入后台模式时,如何在应用中更新位置管理器和计时器? - How can i update location manager and a timer in my app when it goes to background mode? 即使应用程序在 flutter 中被杀死,如何在后台运行倒数计时器功能? - How to run countdown timer functionality in the background even the app is killed in flutter? 如何在应用程序进入后台或终止时运行计时器 - How to run timer though the app entered background or is terminated 如何在后台重复运行计时器&&暂停iOS App - How to run Timer Repeatedly in Background && Suspend iOS App 如何设置计时器在应用程序处于前台和后台运行的时间? - How to set a timer to run when an app is both in foreground and in background? 当应用程序进入和退出后台时更新 ios 中的计时器 - Updating a timer in ios when app goes in and out of background 当应用程序进入后台并返回时,我的NSRunLoop和计时器会发生什么? - What happens to my NSRunLoop and timer when the app goes into background and returns? 在应用中以及后台运行时运行计时器 - Run timer in app and when app is in background Swift:如何在后台运行计时器 - Swift: How to run timer in background
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM