首页 技术 正文
技术 2022年11月20日
0 收藏 359 点赞 4,510 浏览 993 个字

前言

开发中,经常会用到定时执行网络请求、倒计时、计时器等功能,本篇文章介绍在iOS开发中,Swift怎样使用GCD实现这些功能。

执行一次

下面的代码将会在5秒后执行,且只执行一次。

let time: NSTimeInterval = 5.0
let delay = dispatch_time(DISPATCH_TIME_NOW, Int64(time * Double(NSEC_PER_SEC)))dispatch_after(delay, dispatch_get_main_queue()) {
self.getTaskList(false)
}

执行多次

下面的代码是一个60秒倒计时的例子。

var _timeout: Int = 60
let _queue: dispatch_queue_t = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
let _timer: dispatch_source_t = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, _queue)// 每秒执行
dispatch_source_set_timer(_timer, dispatch_walltime(nil, 0), 1 * NSEC_PER_SEC, 0) dispatch_source_set_event_handler(_timer) { () -> Void in if _timeout <= 0 { // 倒计时结束
dispatch_source_cancel(_timer) dispatch_async(dispatch_get_main_queue(), { () -> Void in // 如需更新UI 代码请写在这里
}) } else { print(_timeout)
_timeout-- dispatch_async(dispatch_get_main_queue(), { () -> Void in // 如需更新UI 代码请写在这里
}) }
}dispatch_resume(_timer)

交友互动:

本文首发于马燕龙个人博客,欢迎分享,转载请标明出处。

马燕龙个人博客:http://www.mayanlong.com

马燕龙个人微博:http://weibo.com/imayanlong

马燕龙Github主页:https://github.com/yanlongma

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,997
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,511
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,356
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,139
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,770
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,848