QSLCountdownManager.swift 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. //
  2. // CountDownManager.swift
  3. // QuickSearchLocation
  4. //
  5. // Created by Destiny on 2025/9/24.
  6. //
  7. import UIKit
  8. class QSLCountdownManager {
  9. static let shared = QSLCountdownManager()
  10. private var timer: Timer?
  11. var selectGood: QSLGoodModel?
  12. var remainingSeconds: Int = 900 // 15分钟 = 900秒
  13. var updateHandler: ((String) -> Void)?
  14. var updateHandler1: ((String) -> Void)?
  15. var finishHandler: (() -> Void)?
  16. func startCountdown() {
  17. timer?.invalidate()
  18. timer = nil
  19. if(selectGood == nil){
  20. return
  21. }
  22. remainingSeconds = 900
  23. timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateCountdown), userInfo: nil, repeats: true)
  24. RunLoop.current.add(timer!, forMode: .common)
  25. }
  26. func stopCountdown() {
  27. finishHandler?()
  28. timer?.invalidate()
  29. timer = nil
  30. }
  31. @objc private func updateCountdown() {
  32. remainingSeconds -= 1
  33. if remainingSeconds <= 0 {
  34. stopCountdown()
  35. }
  36. let hours = remainingSeconds / 3600
  37. let minutes = (remainingSeconds % 3600) / 60
  38. let seconds = remainingSeconds % 60
  39. let timeString = String(format: "%02d : %02d : %02d", hours, minutes, seconds)
  40. updateHandler?(timeString)
  41. updateHandler1?(timeString)
  42. }
  43. deinit {
  44. stopCountdown()
  45. }
  46. }