1

I am trying to use the NSTimer to increment the progress bar in my app when recording voice (see the screenshot)App Screenshot

let timedClock = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("Counting:"), userInfo: nil, repeats: true)

    internal func Counting(timer: NSTimer!) {
            if timeCount == 0 {
                //self.timedClock = nil
                stopRecording(self) //performs segue to another view controller
            } else {
                timeCount--;
                self.timer.text = "\(timeCount)"
            }
            print("counting called!")
            progressBar.progress += 0.2
        }

The progress bar works only for the first time after I compile and run the project. When the recording is finished, the app performs segue to another view controller to play the recorded audio. However, when I go back to the view for recording, the timer/progress bar automatically runs. I suspect the NSTimer object is still alive on the NSRunLoop. So I was wondering how to prevent the NSTimer from automatically running.

Inspired by the answer in this SO thread, I tried the following, but the NSTimer still automatically runs.

let timedClock = NSTimer(timeInterval: 1, target: self, selector: "Counting:", userInfo: nil, repeats: true)
        NSRunLoop.currentRunLoop().addTimer(timedClock, forMode: NSRunLoopCommonModes)
Community
  • 1
  • 1
TonyW
  • 18,375
  • 42
  • 110
  • 183

2 Answers2

3

This happens because when your controller created it's properties are automatically initialized. According to Apple Docs (and method's name) scheduledTimerWithTimeInterval create and return scheduled timer. So if you only want create your timer and call it by trigger function use it like this:

class MyClass {

  var timer: NSTimer?
  ...
  func enableTimer() {
    timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("Counting:"), userInfo: nil, repeats: true)
  }

  func disableTimer() {
    timer?.invalidate()
    timer = nil
  }
  ...
}
rkyr
  • 3,131
  • 2
  • 23
  • 38
1

Sorry for the quick self-answer, as I just found out that I can use the invalidate() method to prevent the timer from automatically firing:

timedClock.invalidate()

Hope it helps someone in the future!

TonyW
  • 18,375
  • 42
  • 110
  • 183