From 4562be7e1af1fb248c91a03d451f1947d18e0073 Mon Sep 17 00:00:00 2001 From: MohammadReza Ansary Date: Thu, 16 Nov 2023 13:21:29 +0330 Subject: [PATCH] Fix: Corrected an issue where the Magic timer failed to accurately count down --- Sources/MagicTimer/MagicTimer.swift | 28 ++++++++++++++++------------ 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/Sources/MagicTimer/MagicTimer.swift b/Sources/MagicTimer/MagicTimer.swift index 7bfdce6..a156b58 100644 --- a/Sources/MagicTimer/MagicTimer.swift +++ b/Sources/MagicTimer/MagicTimer.swift @@ -89,11 +89,6 @@ public class MagicTimer { private var counter: MagicTimerCounterInterface private var executive: MagicTimerExecutiveInterface private var backgroundCalculator: MagicTimerBackgroundCalculatorInterface - - // MARK: - Unavailable - /// A elapsed time that can observe - /// - Warning: renamed: "elapsedTimeDidChangeHandler" - public var observeElapsedTime: ((TimeInterval) -> Void)? /// The current state of the timer. /// - Warning: renamed: "lastState" @@ -123,8 +118,9 @@ public class MagicTimer { executive.fire { self.backgroundCalculator.timerFiredDate = Date() self.lastState = .fired + self.setCounter() self.observeScheduleTimer() - } + } } /// Stop counting the timer. @@ -151,6 +147,15 @@ public class MagicTimer { } // MARK: - Private methods + private func setCounter() { + switch countMode { + case .countDown(let fromSeconds): + counter.defultValue = fromSeconds + counter.resetToDefaultValue() + default: break + } + } + // It calculates the elapsed time user was in background. private func calclulateBackgroundTime(elapsedTime: TimeInterval) { switch countMode { @@ -171,17 +176,16 @@ public class MagicTimer { executive.scheduleTimerHandler = { [weak self] in guard let self else { return } - switch self.countMode { + switch countMode { case .stopWatch: - self.counter.add() - self.elapsedTime = self.counter.totalCountedValue + counter.add() + elapsedTime = counter.totalCountedValue case .countDown(let fromSeconds): // Checking if defaultValue plus fromSeconds not going to invalid format(negative seconds). - guard (self.defultValue + fromSeconds).truncatingRemainder(dividingBy: self.effectiveValue).isEqual(to: .zero) else { + guard (defultValue + fromSeconds).truncatingRemainder(dividingBy: effectiveValue).isEqual(to: .zero) else { fatalError("The time does not lead to a valid format. Use valid effetiveValue") } - self.counter.totalCountedValue = fromSeconds guard counter.totalCountedValue.isBiggerThan(.zero) else { executive.suspand { self.lastState = .stopped @@ -189,7 +193,7 @@ public class MagicTimer { return } counter.subtract() - elapsedTime = self.counter.totalCountedValue + elapsedTime = counter.totalCountedValue } } }