Need help to make a countdown timer that waits until it is invalidated to proceed. It also should not be blocking main thread. Any tips?
private var currentCountdownSeconds = 3
private var countdownTimer = Timer()
private func performTimer() {
if secondsToCountDown != 0 {
print(secondsToCountDown)
countdownTimer = Timer(timeInterval: 1, target: self, selector: #selector(handleCountdown), userInfo: nil, repeats: true)
}
}
@objc private func handleCountdown() {
previewView.countdownLabel.text = "\(currentCountdownSeconds)"
currentCountdownSeconds -= 1
print(secondsToCountDown)
if secondsToCountDown == 0 {
countdownTimer.invalidate()
}
}
public func toggleMovieRecording() {
handleTimer()
videoCaptureLogic()
}
public func toggleCapturePhoto() {
handleTimer()
videoCaptureLogic()
}
Try this one if you have to use the countdown in multiple places.
private var currentCountdownSeconds = 3
private var countdownTimer = Timer()
private func performTimer() {
if secondsToCountDown != 0 {
print(secondsToCountDown)
countdownTimer = Timer(timeInterval: 1, target: self, selector: #selector(handleCountdown), userInfo: nil, repeats: true)
}
}
@objc private func handleCountdown() {
previewView.countdownLabel.text = "\(currentCountdownSeconds)"
currentCountdownSeconds -= 1
print(secondsToCountDown)
if secondsToCountDown == 0 {
countdownTimer.invalidate()
NotificationCenter.default.post(notification: NSNotification.Name.init("TimeComplete")
}
}
Now implement the observers for the notification in whichever classes you need it in. The respective selectors will handle the event when countdown completes and the notification is posted.
class Something {
init() {
NotificationCenter.default.addObserver(self, selector: #selector(timerCompleteAction), name: NSNotification.Name.init("TimerComplete"), object: nil)
}
@objc func timerCompleteAction() {
//Do necessary actions
}
}
Something
can be your class which has video capture in which case write that code in the timerCompleteAction
. Then again in the class where you have the audio capture, add the same observer and add the selector method and do the audio capture actions.