简体   繁体   中英

how the countdown timer works in the background

I want to update the counter when the application is thrown into the background and reopened.

First, I added two observers in viewWillAppear like this

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

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

but the countdown timer immediately counts as -1, -2 when the application is first opened. Besides that, I can't update the label the way I want.

 @IBOutlet weak var timeDurationLabel: UILabel!

    var timer = Timer()
    var audioPlayer = AVAudioPlayer()

    var remainder: Int = 0
    var timeDuration: Int = 0
    var countdownInterval: TimeInterval = 0.0

    var currentBackgroundDate = Date()

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        NotificationCenter.default.addObserver(self, selector: #selector(pauseApp1), name: UIApplication.didEnterBackgroundNotification, object: nil)

        NotificationCenter.default.addObserver(self, selector: #selector(startApp1), name: UIApplication.didBecomeActiveNotification, object: nil)
    }

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

    @objc func startApp1() {
        let difference = self.currentBackgroundDate.timeIntervalSince(Date())
        timeDuration = timeDuration + Int(difference)
        self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateCountdown), userInfo: nil, repeats: true)

    }

    @IBAction func startButtonTapped(_ sender: UIButton) {
        self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateCountdown), userInfo: nil, repeats: true)

        self.timeDuration = Int(self.countdownInterval) - (self.remainder % 60)

        self.startButton.initActionBtn(colorType: .gray, title: "START")
        self.coundownPickerButton.isEnabled = false

        self.circularProgress.animate(fromAngle: 0, toAngle: 360, duration: TimeInterval(timeDuration)) {
            completed in
            if completed {
                print("animation stopped, completed")
            }
            else {
                print("animation stopped, was interrupted")
            }
        }
    }

    @objc func updateCountdown() {
        self.timeDuration -= 1
        self.timeDurationLabel.text = timeFormatted(timeDuration)

        if timeDuration == 0 {
            timer.invalidate()

            self.audioPlayer.play()

            self.startButton.initActionBtn(colorType: .green, title: "START")
        }
    }

When you say:

let difference = self.currentBackgroundDate.timeIntervalSince(Date())

This is going to produce a negative value, since you're asking for the time interval from now to when you set the current background date. If you want a positive number you should use:

let difference = Date().timeIntervalSince(self.currentBackgroundDate)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM