倒数计时器在后台如何工作

时间:2019-06-08 20:34:02

标签: ios swift xcode countdowntimer

当应用程序被抛到后台并重新打开时,我想更新计数器。

首先,我像这样在viewWillAppear中添加了两个观察者

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

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

,但是在首次打开应用程序时,倒数计时器立即计数为-1,-2。除此之外,我无法按照自己的方式更新标签。

 @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")
        }
    }

1 个答案:

答案 0 :(得分:0)

当你说:

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

这将产生一个负值,因为您要求的是从现在到设置当前背景日期的时间间隔。如果您想使用正数,则应使用:

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