0

I am quite new to Swift and would love to know how to create a loop that runs some code every 30 seconds? I feel as though it is a basic question but I can't really find what I'm looking for.

Ashish Kakkad
  • 23,586
  • 12
  • 103
  • 136
Max
  • 63
  • 1
  • 7

3 Answers3

0

You can make Use of Timer

Timer.scheduledTimerWithTimeInterval(0.30, target: self, selector: #selector(timerFired), userInfo: userInfo, repeats: true)

timerFired: is the method that gets called after interval

@objc func timerFired() {
      print("Timer Called with interval 30seconds")
}
Anuraj
  • 1,242
  • 10
  • 25
0

You need to use scheduled timer. In viewDidLoad()

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

and func for selector

@objc func YourFuncName() {
      print("every 30seconds")
}
k0le
  • 40
  • 8
0
func startTimer() {
    timer = Timer.scheduledTimer(timeInterval: 30, target: self, selector: #selector(UpdateTimer), userInfo: nil, repeats: true)
}

@objc func UpdateTimer() {
    counter += 1
}

to start

startTimer();

and to stop

timer.invalidate()