The accepted answer from @Fran Martin works great!
Since i was using it in Swift it took me about an hour to figure out the correct Timer()
function. To help the next person who isn't fluent in Objective C here's the Swift version of the accepted answer with some extra functions to invalidate
the timer, to reset the timer back to 00:00
, when to use it in viewWillAppear
, and when to invalidate
it
ALWAYS invalidate
the timer in viewWillDisappear
or viewDidDisappear
otherwise if it is a repeat
timer and it’s running you can get a memory leak
I had an unforeseen problem where the timer kept running even though I would stop it and I found this SO Answer that said you have to stop it before starting it again and when you declare the timer use weak
@IBOutlet weak fileprivate var yourLabel: UILabel!
var timeMin = 0
var timeSec = 0
weak var timer: Timer?
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// if your presenting this vc yourLabel.txt will show 00:00
yourLabel.txt = String(format: "%02d:%02d", timeMin, timeSec)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
resetTimerToZero()
}
// MARK:- recordButton
@IBAction fileprivate func recordButtonTapped(_ sender: UIButton) {
startTimer()
movieFileOutput.startRecording(to: videoUrl, recordingDelegate: self)
}
// MARK:- Timer Functions
fileprivate func startTimer(){
// if you want the timer to reset to 0 every time the user presses record you can uncomment out either of these 2 lines
// timeSec = 0
// timeMin = 0
// If you don't use the 2 lines above then the timer will continue from whatever time it was stopped at
let timeNow = String(format: "%02d:%02d", timeMin, timeSec)
yourLabel.txt = timeNow
stopTimer() // stop it at it's current time before starting it again
timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { [weak self] _ in
self?.timerTick()
}
}
@objc fileprivate func timerTick(){
timeSec += 1
if timeSec == 60{
timeSec = 0
timeMin += 1
}
let timeNow = String(format: "%02d:%02d", timeMin, timeSec)
yourLabel.txt = timeNow
}
// resets both vars back to 0 and when the timer starts again it will start at 0
@objc fileprivate func resetTimerToZero(){
timeSec = 0
timeMin = 0
stopTimer()
}
// if you need to reset the timer to 0 and yourLabel.txt back to 00:00
@objc fileprivate resetTimerAndLabel(){
resetTimerToZero()
yourLabel.txt = String(format: "%02d:%02d", timeMin, timeSec)
}
// stops the timer at it's current time
@objc fileprivate stopTimer(){
timer?.invalidate()
timer = nil
}