代码之家  ›  专栏  ›  技术社区  ›  Osama Naeem

在应用程序进入前台时创建计时器的新实例?

  •  0
  • Osama Naeem  · 技术社区  · 7 年前

    我正在创建一个由用户设置计时器的应用程序。当应用程序转到后台时 timer.invalidate() . 现在我想让计时器在应用程序返回前台时重新启动。我正在创建另一个计时器实例,以便在应用程序发送应用程序位于前台的通知时执行此操作。但是,它没有启动这个功能。

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

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

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

    当它进入后台时,我将使 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()
    
    }
    

    当应用程序返回时,我首先检查 计时器 是否有效,然后创建新计时器。但这个计时器似乎不起作用。

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

    }

    希望您能帮忙!

    1 回复  |  直到 7 年前
        1
  •  1
  •   vacawama    7 年前

    宣布 timer 属性为 weak :

    weak var timer: Timer?
    

    然后设置为 nil 计时器 无效。然后检查一下 定时器 在创建新的之前:

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