需要帮助来建立倒数计时器,该倒数计时器将一直等待直到其无效为止。它也不应阻塞主线程。有提示吗?
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()
}
答案 0 :(得分:0)
您可以使用DispatchGroups。在启动计时器时进入组,在计时器无效时离开组。
private var currentCountdownSeconds = 3
private var countdownTimer = Timer()
private let timerDispatchGroup = DispatchGroup() // Init DispatchGroup
private func performTimer() {
if secondsToCountDown != 0 {
print(secondsToCountDown)
timerDispatchGroup.enter() // Enter DispatchGroup
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()
timerDispatchGroup.leave() // Leave DispatchGroup
}
}
public func toggleMovieRecording() {
performTimer() // I guess it should be performTimer instead of handleTimer?
timerDispatchGroup.notify(queue: .main) { videoCaptureLogic() } // Closure
}
public func toggleCapturePhoto() {
performTimer()
timerDispatchGroup.notify(queue: .main) { videoCaptureLogic() }
}
答案 1 :(得分:0)
如果您必须在多个地方使用倒数计时,请尝试此操作。
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")
}
}
现在在您需要的任何类中实现通知的观察者。当倒计时完成并发布通知时,相应的选择器将处理事件。
class Something {
init() {
NotificationCenter.default.addObserver(self, selector: #selector(timerCompleteAction), name: NSNotification.Name.init("TimerComplete"), object: nil)
}
@objc func timerCompleteAction() {
//Do necessary actions
}
}
Something
可以是您的具有视频捕获功能的课程,在这种情况下,请将该代码写入timerCompleteAction
。然后再次在具有音频捕获功能的类中,添加相同的观察者并添加选择器方法,然后执行音频捕获操作。