封装的类代码

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 = , 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 = //在需要的地方开启倒计时
countdownTimer.DispatchTimer(timeInterval: ) { [weak self] in
self?.handTimer()
} func handTimer() {
self.remainingSeconds -=
if self.remainingSeconds == {//倒计时0秒
self.remainingSeconds =
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
}
}

swift - 封装 GCDTimer 和 NSTimer的更多相关文章

  1. 初识 swift 封装轮播图

    一.简介 换了一家公司.换了一个环境刚开始来公司自然不能有一丝一毫的放松,每天即使是没有什么工作也是看看这个博客.那个源码.尽量让自己更充实.慢慢的开始写几篇博客记录下自己遇到的一些问题和解决方法.其 ...

  2. 纯 Swift 封装的 SQLite 框架:SQLite.swift

    SQLite.swift 是一个使用纯 Swift 语言封装 SQLite3 的操作框架. 特性: 简单的查询和参数绑定接口 安全.自动类型数据访问 隐式提交和回滚接口 开发者友好的错误处理和调试 文 ...

  3. Swift 封装

    前言 封装主要有两大目的:一是为了我们使用数据更加方便,二是为了数据保护. 1.Swift 访问修饰符 在 Swift 语言中,访问修饰符也分为三类,分别是 private.internal.publ ...

  4. swift - 封装百度地图

    1. #import <BaiduMapAPI_Base/BMKBaseComponent.h>//引入base相关所有的头文件 #import <BaiduMapAPI_Map/B ...

  5. swift版的GCD封装

    swift版的GCD封装 说明 本人针对swift封装了GCD,包括GCDQueue,GCDGroup,GCDTimer以及GCDSemaphore,使用较为便利. 源码 https://github ...

  6. Swift 2.0 封装图片折叠效果

    文/猫爪(简书作者)原文链接:http://www.jianshu.com/p/688c491580e3著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”. 用Swift封装图片折叠效果 b ...

  7. swift 自定义图片轮播视图

    Swift封装图片轮播视图: import UIKit class XHAdLoopView: UIView { private var pageControl : UIPageControl? pr ...

  8. Swift和OC相互调

    在项目中不免会有多中语言开发, 不说别的就我个人而言, 之前一直都是用 OC 写的代码, 封装很多工具类, 而苹果新出来 Swift , 现在项目在向 Swift 过渡, 或者新项目是 Swift , ...

  9. Swift & OC 混编 浅析

    转载自:http://www.infoq.com/cn/articles/wangyi-cartoon-swift-mixed-practice?utm_campaign=rightbar_v2&am ...

随机推荐

  1. Spark 编程模型(上)

    Spark的编程模型 核心概念(注意对比MR里的概念来学习) Spark Application的组成 Spark Application基本概念 Spark Application编程模型 回顾sc ...

  2. springBoot----@ConditionalOnxxx相关注解总结

      下面来介绍如何使用@Condition public class TestCondition implements Condition { /** * 只有返回true,才会启用配置 */ pub ...

  3. 常用数据库4 mongodb

    知识内容: 1.mongodb介绍与基本使用 2.mongodb操作 一.mongodb介绍与基本使用 1.mongodb介绍 Mongodb是一款强大,灵活,且易于扩展的通用型数据库.它能扩展出非常 ...

  4. C#_Markov_心得感想

    来到实验室正好有一个月了,趁着端午假期稍微轻松一些,在大改程序体系之前,想将自己在这30天中工作之一Markov回顾一下,将从真实的写程序中学习到的知识.思想记录下来.希望能和大家积极讨论! 本文会以 ...

  5. Activity服务类-3 FormService服务类

    1.获取//通过流程定义ID获取表单字段集合StartFormData startFormData = formService.getStartFormData(processDefinitionId ...

  6. mysql 自动执行事件

    首先配置mysql的配置文件my.ini,  加上event_scheduler = 1  开启自动执行事件配置 demo drop event event_test; CREATE EVENT ev ...

  7. Mysql 游标使用

    BEGIN #shopsId 商家ID #accountDay 10位日期 -- 定义一个或者多个 变量来接收 游标查询的列值 DECLARE receiptContentId INT; -- 遍历数 ...

  8. 分享 - 27 个机器学习、数学、Python 速查表

      转载自:伯乐在线 - iPytLab,原文链接,侵删 机器学习涉及到的方面非常多.当我开始准备复习这些内容的时候,我找到了许多不同的”速查表”, 这些速查表针对某一主题都罗列出了所有我需要知道的知 ...

  9. (3)shiro自定义realm

    上面一章说到shiro的认证和授权最底层就是调用realm的getAuthorizationInfo(获取用户的角色和资源)和getAuthenticationInfo(校验账号密码是否正确)两个方法 ...

  10. scala--函数式对象

    函数式对象 这次写点关于函数式对象的吧 class Rational(n:Int, d:Int) { // n,d 为类参数,scala会创造出同样带有这两个参数的主构造器.如果这个类没有主体,可以不 ...