封装的类代码
import UIKit /// 控制定时器的类 class ZDTimerTool: NSObject { /// 定时器 // private var timer: Timer? /// GCD定时器 private var GCDTimer: DispatchSourceTimer? /// GCD定时器的挂起状态 private var isSuspend: Bool = false override init() { super.init() } deinit { // 对象在销毁前会销毁定时器,所以使用定时器应该设置全局的属性 // self.invaliTimer() self.invaliGCDTimer() DDLOG(message: "deinit: ZDTimerTool") } // /// 设置定时器 // func initilAndStartTimer(timeInterval: TimeInterval,handleBlock:@escaping (() -> Void)) { // self.timer = Timer.scheduledTimer(withTimeInterval: timeInterval, repeats: true, block: { t in // handleBlock() // }) // } // /// 暂停或者重启定时器定时器 // func stopOrStartTimer(isStop: Bool) { // self.timer?.fireDate = isStop == true ? Date.distantFuture : Date.distantPast // } // /// 销毁定时器 // func invaliTimer() { // self.timer?.invalidate() // self.timer = nil // } } /// GCD定时器相关方法 extension ZDTimerTool{ /// 初始化得到GCD定时器 func DispatchTimer(delayTime: Double = 0 , timeInterval: TimeInterval , handleBlock:@escaping (() -> Void)) { if self.GCDTimer == nil { self.GCDTimer = DispatchSource.makeTimerSource(flags: [], queue: DispatchQueue.main) self.GCDTimer?.schedule(deadline: DispatchTime.now(), repeating: timeInterval) self.GCDTimer?.setEventHandler{ DispatchQueue.main.async { handleBlock() } } }else{ self.GCDTimer?.setEventHandler{ DispatchQueue.main.async { handleBlock() } } } self.GCDTimer?.schedule(deadline: DispatchTime.now(), repeating: timeInterval) // self.GCDTimer?.schedule(wallDeadline: DispatchWallTime.now(), repeating: timeInterval) DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + delayTime) { [weak self] in self?.GCDTimer?.resume() } } /// 暂停或者重启GCDTimer func stopOrResumeGCDTimer(isStop: Bool){ isStop == true ? self.GCDTimer?.suspend() : self.GCDTimer?.resume() self.isSuspend = isStop } /// 销毁GCD定时器 func invaliGCDTimer() { if self.isSuspend == true { self.GCDTimer?.resume() } self.GCDTimer?.cancel() //销毁前不能为suspend(挂起状态) self.GCDTimer = nil } }
使用方法:
属性 timer 和时间 //倒计时 var countdownTimer = ZDTimerTool() // remainingSeconds代表当前倒计时剩余的秒数 var remainingSeconds: Int = 60
//在需要的地方开启倒计时 countdownTimer.DispatchTimer(timeInterval: 1) { [weak self] in self?.handTimer() } func handTimer() { self.remainingSeconds -= 1 if self.remainingSeconds == 0{//倒计时0秒 self.remainingSeconds = 60 self.sendButton.setTitle("重新发送", for: .normal) self.sendButton.backgroundColor = UIColor.red self.sendButton.isEnabled = true self.countdownTimer.stopOrResumeGCDTimer(isStop: true) }else{ sendButton.setTitle("\(remainingSeconds)秒后重新获取", for: .normal) self.sendButton.backgroundColor = UIColor.gray sendButton.isEnabled = false } }