Search code examples
swiftxcodeuilabel

Update label when returning from background


I have a problem trying to update the label when the app returns from Background. I already implemented LocalNotifications for my timer app and is working perfect but when I return to the app the countdown label is stopped. So basically I am trying to find the way to update the countdown label with the current time left. I would appreciate any help!

My Code is here:

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


    }

Solution

  • You need to add your observers inside viewDidLoad(), NOT in viewDidAppear

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