QSLCountdownManager.swift 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. didSet{
  13. if(oldValue != nil){
  14. NotificationCenter.default.post(
  15. name: Notification.Name("QSLHomeRefreshCouponViewNoti"),
  16. object: nil,
  17. userInfo: nil
  18. )
  19. }
  20. }
  21. }
  22. var remainingSeconds: Int = 900 * 1000 // 15分钟 = 900秒
  23. var updateHandler: ((String) -> Void)?
  24. var updateHandler1: ((String) -> Void)?
  25. var finishHandler: (() -> Void)?
  26. func startCountdown() {
  27. timer?.invalidate()
  28. timer = nil
  29. if(selectGood == nil){
  30. return
  31. }
  32. remainingSeconds = 900 * 1000
  33. timer = Timer.scheduledTimer(timeInterval: 0.001, target: self, selector: #selector(updateCountdown), userInfo: nil, repeats: true)
  34. RunLoop.current.add(timer!, forMode: .common)
  35. }
  36. func checkIsCountDown() -> Bool{
  37. if let curTimer = timer {
  38. return true
  39. }else{
  40. return false
  41. }
  42. }
  43. func stopCountdown() {
  44. finishHandler?()
  45. timer?.invalidate()
  46. timer = nil
  47. }
  48. @objc private func updateCountdown() {
  49. remainingSeconds -= 1
  50. if remainingSeconds <= 0 {
  51. stopCountdown()
  52. }
  53. let totalSeconds = remainingSeconds / 1000
  54. let minutes = totalSeconds / 60
  55. let seconds = totalSeconds % 60
  56. let milliseconds = remainingSeconds % 1000
  57. // 格式:MM:SS:SSS(例如 "14:59:500")
  58. let timeString = String(format: "%02d : %02d : %03d", minutes, seconds, milliseconds)
  59. updateHandler?(timeString)
  60. updateHandler1?(timeString)
  61. }
  62. deinit {
  63. stopCountdown()
  64. }
  65. }