I need to execute a function every 10 seconds, using swift. But i dont know how to proceed. I know I have to use a timer, but didnt find useful tutorial for this.
Thank you
I need to execute a function every 10 seconds, using swift. But i dont know how to proceed. I know I have to use a timer, but didnt find useful tutorial for this.
Thank you
Do read this.
override func viewDidLoad() {
super.viewDidLoad()
//Swift 3 selector syntax
var timer = Timer.scheduledTimer(timeInterval: 0.4, target: self, selector: #selector(self.update), userInfo: nil, repeats: true);
//Swift 2.2 selector syntax
var timer = NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: #selector(MyClass.update), userInfo: nil, repeats: true)
//Swift <2.2 selector syntax
var timer = NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: "update", userInfo: nil, repeats: true)
}
// must be internal or public.
func update() {
// Something cool
}
You can do it using a NSTimer and a RunLoop:
func startTimer(){
let timer = Timer.scheduledTimer(timeInterval: 10, target: self, selector: #selector(yourFunction), userInfo: nil, repeats: true)
RunLoop.current.add(timer, forMode: RunLoopMode.commonModes)
}
func yourFunction(){
//doStuff
}