Swift之dispatch_source实现多线程定时关闭功能
发布时间:2020-12-14 02:01:27 所属栏目:百科 来源:网络整理
导读:由于在项目中需要用到定时关闭音频功能,本来打算用NSTimer的,可是写起来并不是那么精简好用,所以又在网上找到相关的实例,结合自己项目需要,就写出了如下代码,还请大家指教,废话不多说: import UIKitclass TimeCountdown: NSObject { var content: String = "
由于在项目中需要用到定时关闭音频功能,本来打算用NSTimer的,可是写起来并不是那么精简好用,所以又在网上找到相关的实例,结合自己项目需要,就写出了如下代码,还请大家指教,废话不多说: import UIKit
class TimeCountdown: NSObject {
var content: String = "未开启" //倒计时要展示的内容
var status: Bool = false //定时器状态
private var timer: dispatch_source_t?
private var currentQueue: dispatch_queue_t?
//这里使用了单利
class func shareInstance() -> TimeCountdown {
struct singleton {
static var predicate: dispatch_once_t = 0
static var instance: TimeCountdown? = nil
}
//只调用一次
dispatch_once(&singleton.predicate,{ () -> Void in
singleton.instance = TimeCountdown()
})
return singleton.instance!
}
//调用该对象方法启动倒计时,minutes为传入的分钟数
func startTimeOut(minutes: Int) {
var timeOut = minutes * 60 //秒数,用于计算
if timer != nil {
dispatch_source_cancel(self.timer!)
timer = nil;
}
//不开启
if (minutes == 0) {
self.content = "未开启"
self.status = false
dispatch_async(dispatch_get_main_queue(),{ () -> Void in
NSNotificationCenter.defaultCenter().postNotificationName("startTimeOut",object: nil,userInfo: nil)
})
return
}
if currentQueue == nil {
currentQueue = dispatch_queue_create("com.gcd.timeout",nil)
}
self.status = true
timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,0,currentQueue)
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(self.timer!)
self.content = "未开启"
self.status = false
dispatch_async(dispatch_get_main_queue(),{ () -> Void in
//暂停播放器
AudioPlayerViewController.pausePlayer()
})
} else {
var minutes = timeOut / 60
var seconds = timeOut % 60
self.content = "(minutes)分(seconds)秒后,将暂停播放广播"
--timeOut
}
dispatch_async(dispatch_get_main_queue(),{ () -> Void in
//每秒发送一次通知,用于更新要显示的倒计时时间(在制定控制器监听该通知)
NSNotificationCenter.defaultCenter().postNotificationName("startTimeOut",userInfo: nil)
})
})
//启动 dispatch source
dispatch_resume(timer!)
}
}
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- iphone – xcode基本游戏模板
- Oracle:将数字转换为除英语之外的其他语言的单词
- c# – 我们如何检测COM Interop应用程序中的内存泄漏?
- reactjs – 如何使用redux-form处理提交
- PostgreSQL数据库 OLTP高并发请求性能优化
- 设计模式6大原则之里氏替换原则
- PostgreSQL 9.4 Released! 18th December 2014
- 一个de两种意思——谈谈Dojo define 和declare的区别
- ruby-on-rails-4 – sidekiq – 警告:ArgumentError:参数
- 关于XML fragments parsed from previous mappers already