2

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.

Metabble
  • 11,773
  • 1
  • 16
  • 29
lwiu
  • 179
  • 1
  • 9
  • There's an alternate option for you, if you're just looking to create a delay when the view loads, an `NSTimer` is likely overkill. You can use GCD to add a delay without the `NSTimer` overhead: `dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(2.0 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { self.goTakingPhoto() }` It looks a lot more complicated than it is, and I use a macro (Thanks to [Dash][1]) so I don't actually have to type it out each time. [1]: https://itunes.apple.com/us/app/dash-3-api-docs-snippets/id449589707?mt=12&uo=4&at=11lMGu – Dave Wood Jul 08 '15 at 01:37

2 Answers2

3

Try this:

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

func goTakingPhoto() {
   // doSomething
}
Hayley Guillou
  • 3,953
  • 4
  • 24
  • 34
0

I found it works with NSTimer.scheduledWithTimeInterval(...). And you don't have to add timer.fire() otherwise the func will be invoked imediately

Reference here

Community
  • 1
  • 1
lwiu
  • 179
  • 1
  • 9