Search code examples
iosswiftuikit

How do you make a timer controller with a condition?


I'm a beginner in Swift and have a task to change the bottom sheet message when the process of the app doesn't work in three minutes. So, the message will change from "available" to "not available" if the process does not work.

I found code syntax like:

Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(fireTimer), userInfo: nil, repeats: true)

What I think:

var waktu = 0
Timer.scheduledTimer(withTimeInterval: 180.0, repeats: false) {

    if waktu == 180 {
        timer.invalidate()
        //run the change message function
        
    }
}

Solution

  • You can add observer on your property, so it will invalidate the timer when condition met, like so:

        var waktu = 0 {
            didSet {
                if waktu == 180 {
                    timer.invalidate()
                }
            }
        }