kyle-c
11/19/2017 - 11:55 AM

Set scheduled task in Swift

This snippet help to create scheduled task with timer in swift (with repeat, or not)

Tags: Timer - NSTimer - timer - nstimer

import UIKit

class MyClass: UIViewController {

  var taskManager = NSTimer()
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    //Swift 2.3
    taskManager = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(MyClass.functionToPerform), userInfo: nil, repeats: true) //Set repeats to false if needed
    NSRunLoop.currentRunLoop().addTimer(taskManager, forMode: NSRunLoopCommonModes)
    
    
    //Swift 3
    taskManager = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(MyClass.updateInfo), userInfo: nil, repeats: true) //Set repeats to false if needed
    RunLoop.main.add(taskManager, forMode: RunLoopMode.commonModes)
  }
}
  
  func functionToPerform(){
    //perform actions
  }
}