NSTimer does not work on swift

advertisements

This question already has an answer here:

  • NSTimer timerWithTimeInterval: not working 3 answers

I wrote this code to use a Timer inside of a View Controller:

var timer:NSTimer!
override func viewDidLoad() {
    super.viewDidLoad()
    timer = NSTimer(timeInterval: 2, target: self, selector: "goTakingPhoto", userInfo: nil, repeats: false)
    timer.fire()
    // Do any additional setup after loading the view.
}
 func goTakingPhoto(){
   // doSomething
}

But the function goTakingPhoto is invoked immediately, not after 2 seconds. Can anyone help me? Many thanks.


Try this:

override func viewDidLoad() {
    super.viewDidLoad()
    var timer = NSTimer.scheduledTimerWithTimeInterval(2, target: self, selector: Selector("goTakingPhoto"), userInfo: nil, repeats: false)}
}

func goTakingPhoto() {
   // doSomething
}