swift Timer not responding from method call

266 views Asked by At

Something really odd is happening with my code.

I made a rather simple Timer function that is triggered by button. The button calls a first method, then the method use another function to do the counting, then it triggers something when the time's up.
And everything works fine.

here's the code.

// This is the declaration of the launch button. 
@IBAction func playLater(_ sender: Any) {

    if isTimerRunning == false {
        runTimer()

    }
}

var seconds = 10
var timer = Timer()

var isTimerRunning = false
var resumeTapped = false

//the timer function that sets up the duration and launches the counting. 
func runTimer() {
    timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: (#selector(self.updateTimer)), userInfo: nil, repeats: true)
    isTimerRunning = true
}

//this part is making sure that you go from 10 to 0 and when it's at 0, something happens. In this very case, it plays a song. 
@objc func updateTimer() {
    if seconds < 1 {
        timer.invalidate()
        isTimerRunning = false


        playNow((Any).self)

    } else {
        seconds -= 1
        timerLabel.text = timeString(time: TimeInterval(seconds))
        timerLabel.text = String(seconds)

    }
}

The thing is that I also want to be able to triger that same function from the Apple Watch. I made a WCSession that is working well, the messages are passing, it's ok. So I'm using this code to launch the same function when the user pushes a button on the apple Watch. That part of the code is on the same iOS swift file.

  @available(iOS 9.0, *)
func session(_ session: WCSession, didReceiveMessage message: [String : Any]) {
    // do something
    isTimerRunning = false
    playLater(Any.self)      
}

As you can see, I'm not even trying to add some code, I just call the same function used with the iOS button. But this time, it's not working. The first part of the method is responding, I saw that runTimer() is working, but it's not going to updateTimer().

Maybe I'm missing something here, but, what is the difference ? Why if it comes from the push of a button it's working, and if it's called directly from "the inside" nothing happens ?

If you have any educated guesses, or even, clues, I'd be grateful. Thanks !

0

There are 0 answers