как таймер обратного отсчета работает в фоновом режиме - PullRequest
0 голосов
/ 08 июня 2019

Я хочу обновить счетчик, когда приложение переходит в фоновый режим и открывается снова.

Сначала я добавил двух наблюдателей в 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 голосов
/ 09 июня 2019

Когда вы говорите:

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

Это приведет к отрицательному значению, так как вы запрашиваете временной интервал с этого момента до того момента, когда вы устанавливаете текущую фоновую дату.Если вы хотите получить положительное число, вы должны использовать:

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