Pavel Pavel - 1 month ago 4x
iOS Question

Swift: How to make a method to be called every 10 seconds

In my main ViewController ViewDidLoad, I have the following code that calls the "tick" method every second.

self.timerTick = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(ViewController.tick), userInfo: nil, repeats: true)

In the "tick" method, I check if a boolean value is true every second, and if true, I need to call a second method called SpeakText(), but I want to call the SpeakText() only once every 10 seconds. How do I do this?


Create a class property to keep track of the time since the last SpeakText. Update it each time tick is called, and reset it to 0 when SpeakText is called:

var secondsSinceSpeakText = 10

func tick() {
    secondsSinceSpeakText += 1
    if boolFlag && secondsSinceSpeakText >= 10 {
        secondsSinceSpeakText = 0

Note: Starting secondsSinceSpeakText with an initial value of 10 will allow the first SpeakText to happen immediately.