How to show Multiple timers at same screen using one function in Swift ios

Viewed 44

In my app I have spots on which a user can tap to unlock them, a user can unlock multiple spots at the same time and there can be different number of spots every time, whenever a user unlocks a spot i want to show a timer of 60 seconds on the unlocked spot, So, there can be multiple timers on same screen all having different counts. For example if a user unlocks 2 spots with the difference of 30 seconds. the timer on spot 1 should be 30 seconds left and spot 2 should be 60 seconds left. I only have 1 function for doing this task I can easily show timer on 1 spot but showing them on multiple places, multiple times is very complex. I am sharing a picture too for reference. any help would be appreciated.

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

@objc func updateCounter() {
if counter > 0 {

        let time = Int(counter/60)
        let dec = Int(counter.truncatingRemainder(dividingBy: 60))
        spotTiming = String(time) + ":" + String(dec)
        }
        counter -= 1
}

i want to show timers where counter is written

1 Answers

You can use a timer as a trigger to update the UI every x period (example: 0.5s). You save time remaining every spots at a variable as Array and reduce each element when timer was triggered.

let step = TimeInterval(0.5)
timer = Timer.scheduledTimer(timeInterval: step, target: self, selector: #selector(updateCounter), userInfo: nil, repeats: true)

var timer_remainings = [TimeInterval]()

@objc func updateCounter() {
    for (index, item) in timer_remainings.enumerated() {
        timer_remainings[index] = max(0.0, timer_remainings - step)
    }
    
    // Update UI
    updateUI()
}
Related