From 2e8caa7ee33a6245bcd12362db99770e6588f896 Mon Sep 17 00:00:00 2001 From: junha Date: Thu, 28 Dec 2023 17:26:57 +0900 Subject: [PATCH] =?UTF-8?q?=E2=9A=93=EF=B8=8F::=20[#22]=20MindGaGymKitTime?= =?UTF-8?q?r=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Sources/MindGymKit /MindGaGymKitTimer.swift | 77 +++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 Sources/MindGymKit /MindGaGymKitTimer.swift diff --git a/Sources/MindGymKit /MindGaGymKitTimer.swift b/Sources/MindGymKit /MindGaGymKitTimer.swift new file mode 100644 index 0000000..e83d3e2 --- /dev/null +++ b/Sources/MindGymKit /MindGaGymKitTimer.swift @@ -0,0 +1,77 @@ +// +// File.swift +// +// +// Created by 박준하 on 12/28/23. +// + +import UIKit +import RxSwift + +// MARK: - MindGaGymKitTimer +open class MindGaGymKitTimer: NSObject, TimerControl { + + private var initCounter: Double = 0.0 + private var counter: Double = 0.0 + private var timer: Timer? + private var lapTimes: [Double] = [] + private let timerSubject = PublishSubject() + private let recordSubject = PublishSubject<[String]>() + + public var timeUpdate: Observable { + return timerSubject.asObservable() + } + + public func setting(count: Double) { + initCounter = count + self.counter = count + let timeString = self.timeString(from: self.counter) + self.timerSubject.onNext(timeString) + } + + public func start() { + timer = Timer.scheduledTimer(withTimeInterval: 0.035, repeats: true) { [weak self] _ in + guard let self = self else { return } + self.counter -= 0.035 + let timeString = self.timeString(from: self.counter) + self.timerSubject.onNext(timeString) + } + } + + public func stop() { + timer?.invalidate() + timer = nil + } + + public func restart() { + counter = initCounter + let timeString = self.timeString(from: self.counter) + self.timerSubject.onNext(timeString) + } + + public func reset() { + counter = 0.0 + initCounter = 0.0 + let timeString = self.timeString(from: self.counter) + self.timerSubject.onNext(timeString) + } + + public func record() { + lapTimes.append(counter) + let lapTimesString = lapTimes.map { timeString(from: $0) } + recordSubject.onNext(lapTimesString) + } + + private func timeString(from counter: Double) -> String { + let hours: String = String(format: "%02d", Int(counter / 3600)) + let minutes: String = String(format: "%02d", Int(counter / 60)) + let seconds: String = String(format: "%02d", Int(counter.truncatingRemainder(dividingBy: 60))) + if counter / 3600 >= 1 { + return "\(hours) : \(minutes) : \(seconds)" + } else if counter / 60 > 1 { + return "\(minutes) : \(seconds)" + } else { + return "\(minutes) : \(seconds)" + } + } +}