enum RepeatingTimerState {
case suspended
case resumed
}
protocol PrompterTimeHelperProtocol: NSObjectProtocol {
func eventHandler(_ timer: RepeatingTimer)
func statusChange(_ status: RepeatingTimerState)
}
/// 提词器定时器逻辑 helper
class RepeatingTimer {
// MARK: - 外部属性
weak var delegate: PrompterTimeHelperProtocol?
// MARK: - 内部属性
private let timeInterval: DispatchTimeInterval
private var state: RepeatingTimerState = .suspended {
didSet {
delegate?.statusChange(state)
}
}
private lazy var timer: DispatchSourceTimer = {
let t = DispatchSource.makeTimerSource(flags: .strict, queue: DispatchQueue.global())
t.schedule(deadline: .now() + self.timeInterval, repeating: self.timeInterval)
t.setEventHandler(handler: { [weak self] in
guard let self = self else { return }
self.eventHandler()
})
return t
}()
required init(timeInterval: DispatchTimeInterval) {
self.timeInterval = timeInterval
}
deinit {
cancel()
}
}
// MARK: - About Public Custom Action
extension RepeatingTimer {
func resume() {
if state == .resumed {
return
}
state = .resumed
timer.resume()
}
func suspend() {
if state == .suspended {
return
}
state = .suspended
timer.suspend()
}
func cancel() {
timer.setEventHandler {}
timer.cancel()
/*
If the timer is suspended, calling cancel without resuming
triggers a crash. This is documented here https://forums.developer.apple.com/thread/15902
*/
resume()
delegate = nil
}
}
// MARK: - About Private Custom Action
private extension RepeatingTimer {
func eventHandler() {
DispatchQueue.main.async {
self.delegate?.eventHandler(self)
}
}
}
DispatchSourceTimer 简易封装 - Swift版
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- JSON对象转Model其实是一个编解码的过程,Swift原生提供Codable协议负责编解码的工作,遵循协议的对...
- 不多说,轮播图是开发中必要一项技能,直接上代码: 先说我的思路:首次继承于UIScrollView类自定义MySc...
- UserDefaults 这个东西相信大家都用过,但是它的存取需要写很长的方法调用,感觉很笨拙。我们为何不用 su...
- 关于网络请求,swift版本的最多的就是alamofire,是afn的swift版本,git上有详细用法,这里就不...