从后台返回时更新标签

Update label when returning from background

当应用 return 从后台更新标签时我遇到了问题。我已经为我的计时器应用程序实现了 LocalNotifications,并且工作完美,但是当我 return 到应用程序时,倒计时标签停止了。 所以基本上我试图找到用当前剩余时间更新倒计时标签的方法。我将不胜感激任何帮助!

我的代码在这里:

    var timer = Timer()
    var teas = Teas()
    var isTimerRunning = false
    var alarmSound = AVAudioPlayer()
    var playing = false
    var initialValueOfTime = 0


    var timeDuration = 0
    var currentBackgroundDate = Date()

override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        NotificationCenter.default.addObserver(self, selector: #selector(teasGoBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(runTimer), name: UIApplication.didBecomeActiveNotification, object: nil)

    }



@objc func runTimer() {


        if isTimerRunning {
            teas.time -= 1
            let difference = Date().timeIntervalSince(self.currentBackgroundDate)
            timeDuration = timeDuration + Int(difference)

            if teas.time <= 0 {
                timer.invalidate()
                startButton.setTitle("Done", for: .normal)
            }
        }
        else {
            teas.time = initialValueOfTime
        }

 @objc func resetTimer() {

        timer.invalidate()
        runTimer()

    }

    @objc func teasGoBackground() {
           timer.invalidate()
           currentBackgroundDate = Date()
       }


  @IBAction func startButtonPressed(_ sender: Any) {


        if !isTimerRunning {
            navigationItem.hidesBackButton = true
            isTimerRunning = true
            timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(runTimer), userInfo: nil, repeats: true)
            print("time")
            startButton.setTitle("Stop Brewing", for: .normal)
        } else {
            navigationItem.hidesBackButton = false
            isTimerRunning = false
            resetTimer()
            startButton.setTitle("Start Brewing", for: .normal)
        }


    }

您需要在 viewDidLoad() 中添加您的观察者,NOTviewDidAppear

override func viewDidLoad() {
    super.viewDidLoad()

    NotificationCenter.default.addObserver(self, selector: #selector(teasGoBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(runTimer), name: UIApplication.didBecomeActiveNotification, object: nil)

}

我终于在我的项目中实现了这段代码并成功了!

if let date = UserDefaults.standard.object(forKey: "teastart\(teas.id)") as? Date {
                let now = Date()
                let secondsTillNow = now.timeIntervalSince1970
                let previousSeconds = date.timeIntervalSince1970
                let timeSinceStart = secondsTillNow - previousSeconds
                let time = Int(timeSinceStart)
                if time > teas.time {
                    initialValueOfTime = teas.time

                    startButton.setTitle(NSLocalizedString("Start Brewing", comment: ""), for: .normal)
                    UserDefaults.standard.set(false, forKey: "timerunning\(teas.id)")
                } else {
                    initialValueOfTime = teas.time - time

                    startButton.setTitle(NSLocalizedString("Stop Brewing", comment: ""), for: .normal)
                    UserDefaults.standard.set(true, forKey: "timerunning\(teas.id)")
                }
            } else {
                initialValueOfTime = teas.time
                UserDefaults.standard.set(false, forKey: "timerunning\(teas.id)")
            }