-4

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

2 Answers2

3

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
}
Community
  • 1
  • 1
ystack
  • 1,736
  • 11
  • 22
1

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
    }
Juan Curti
  • 2,794
  • 18
  • 35