由于在项目中需要用到定时关闭音频功能,本来打算用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!)
}
}