美文网首页
swift GCD代替Timer的计时器

swift GCD代替Timer的计时器

作者: 彼岸花下的暗影 | 来源:发表于2019-05-10 14:58 被阅读0次
class WTGCDTimer: NSObject {
    
    static var codeTimer: DispatchSourceTimer?

    class func start(_ timeInterval: TimeInterval = 1,_ totolTimeInterval: TimeInterval = Double(MAXFLOAT), animation: @escaping (_ isFinish: Bool)->()){
 
        var timeCount = totolTimeInterval
      
        WTGCDTimer.codeTimer = DispatchSource.makeTimerSource(queue: DispatchQueue.global())
 
        WTGCDTimer.codeTimer?.schedule(deadline: .now(), repeating: timeInterval)
        
        var isFinish = false
        
        WTGCDTimer.codeTimer?.setEventHandler(handler: {
            
            timeCount = timeCount - timeInterval
          
            if timeCount == 0 {
                WTGCDTimer.codeTimer?.cancel()
                isFinish = true
            }
            
            DispatchQueue.main.async {
                animation(isFinish)
            }
            
        })

        WTGCDTimer.codeTimer?.resume()
 
    }
    
    class func stop() {
        WTGCDTimer.codeTimer?.cancel()
    }

}

相关文章

网友评论

      本文标题:swift GCD代替Timer的计时器

      本文链接:https://www.haomeiwen.com/subject/rijaoqtx.html