由于在项目中需要用到定时关闭音频功能,本来打算用NSTimer的,可是写起来并不是那么精简好用,所以又在网上找到相关的实例,结合自己项目需要,就写出了如下代码,还请大家指教,废话不多说:
- import UIKit
-
- class TimeCountdown: NSObject {
-
- var content: String @H_403_10@= "未开启" //倒计时要展示的内容
- var status: Bool @H_403_10@= false //定时器状态
- private var timer: dispatch_source_t@H_403_10@?
- private var currentQueue: dispatch_queue_t@H_403_10@?
-
- //这里使用了单利
- class func shareInstance() @H_403_10@-> TimeCountdown {
- struct singleton {
- static var predicate: dispatch_once_t @H_403_10@= 0
- static var instance: TimeCountdown@H_403_10@? @H_403_10@= nil
- }
- //只调用一次
- dispatch_once(@H_403_10@&singleton.predicate,{ () @H_403_10@-> Void in
- singleton.instance @H_403_10@= TimeCountdown()
- })
- return singleton.instance@H_403_10@!
- }
-
- //调用该对象方法启动倒计时,minutes为传入的分钟数
- func startTimeOut(minutes: Int) {
- var timeOut @H_403_10@= minutes @H_403_10@* 60 //秒数,用于计算
- if timer @H_403_10@!= nil {
- dispatch_source_cancel(self.timer@H_403_10@!)
- timer @H_403_10@= nil;
- }
-
- //不开启
- if (minutes @H_403_10@== 0) {
- self.content @H_403_10@= "未开启"
- self.status @H_403_10@= false
- dispatch_async(dispatch_get_main_queue(),{ () @H_403_10@-> Void in
- NSNotificationCenter.defaultCenter().postNotificationName("startTimeOut",object: nil,userInfo: nil)
- })
- return
- }
-
- if currentQueue @H_403_10@== nil {
- currentQueue @H_403_10@= dispatch_queue_create("com.gcd.timeout",nil)
- }
- self.status @H_403_10@= true
- timer @H_403_10@= dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,0,currentQueue)
- dispatch_source_set_timer(timer@H_403_10@!,dispatch_walltime(nil,0),1@H_403_10@*NSEC_PER_SEC,0)
- dispatch_source_set_event_handler(timer@H_403_10@!,{ () @H_403_10@-> Void in
- if (timeOut @H_403_10@<= 0) {
- dispatch_source_cancel(self.timer@H_403_10@!)
- self.content @H_403_10@= "未开启"
- self.status @H_403_10@= false
- dispatch_async(dispatch_get_main_queue(),{ () @H_403_10@-> Void in
- //暂停播放器
- AudioPlayerViewController.pausePlayer()
- })
- } else {
- var minutes @H_403_10@= timeOut @H_403_10@/ 60
- var seconds @H_403_10@= timeOut @H_403_10@% 60
- self.content @H_403_10@= "\(minutes)分\(seconds)秒后,将暂停播放广播"
- @H_403_10@--timeOut
- }
- dispatch_async(dispatch_get_main_queue(),{ () @H_403_10@-> Void in
- //每秒发送一次通知,用于更新要显示的倒计时时间(在制定控制器监听该通知)
- NSNotificationCenter.defaultCenter().postNotificationName("startTimeOut",userInfo: nil)
- })
- })
- //启动 dispatch source
- dispatch_resume(timer@H_403_10@!)
- }
-
-
-
- }