在应用程序进入前台时创建Timer的新实例? [英] Creating a new instance of Timer when app enters foreground?

查看:67
本文介绍了在应用程序进入前台时创建Timer的新实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个应用,其中用户设置了计时器.当应用程序进入后台时,timer.invalidate().现在,我希望计时器在应用程序回到前台时再次启动.当应用程序发送通知应用程序在前台的通知时,我正在创建另一个计时器实例来执行此操作.但是,它没有触发该功能.

I am creating an app where a timer is set by the user. When the app goes to the background, the timer.invalidate(). Now I want the timer to start again when the app comes back to the foreground. I am creating another instance of timer to do it when the app sends notification that app is in the foreground. However, it's not firing the function.

Viewdidload()中,我正在创建一个计时器:

In Viewdidload() I am creating a timer:

 timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(handleCountdown), userInfo: nil, repeats: true)
    RunLoop.current.add(self.timer!, forMode: RunLoop.Mode.common)

然后我收到通知,以检查该应用程序是在后台还是在前台:

And then I have notifications that check if the app is in background or in foreground:

当它进入后台时,我将使timer无效.

When it enters background I am invalidating the timer.

  @objc func applicationDidEnterBackground() {
    let defaults = UserDefaults.standard
    let quitTime = Date()
    defaults.set(quitTime, forKey: "quitTimeKey") //Storing the time of quit in UserDefaults
    timer?.invalidate()

}

当应用退出时,我首先检查timer是否为isValid,然后创建一个新计时器.但是此计时器似乎不起作用.

When the app gets back out, I first check if the timer is isValid or not, and then create a new timer. But this timer doesn't seem to work.

@objc func appEntersForeground() {
    calculateTimeLeft()
    if let timer = timer {
        if (!timer.isValid)
        {
            Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(handleCountdown), userInfo: nil, repeats: true)
        }
    }

}

这里的一些帮助将不胜感激!

Some help here will be appreciated!

推荐答案

将您的timer属性声明为weak:

weak var timer: Timer?

然后,当timer无效时,它将被设置为nil.然后只需在创建新的之前检查timer是否为nil:

Then it will be set to nil when the timer is invalidated. Then just check if timer is nil before creating a new one:

@objc func appEntersForeground() {
    calculateTimeLeft()
    if timer == nil {
        timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(handleCountdown), userInfo: nil, repeats: true)
    }
}

这篇关于在应用程序进入前台时创建Timer的新实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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