Swift之dispatch_source实现多线程定时关闭功能

前端之家收集整理的这篇文章主要介绍了Swift之dispatch_source实现多线程定时关闭功能前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

由于在项目中需要用到定时关闭音频功能,本来打算用NSTimer的,可是写起来并不是那么精简好用,所以又在网上找到相关的实例,结合自己项目需要,就写出了如下代码,还请大家指教,废话不多说:

  1. import UIKit
  2.  
  3. class TimeCountdown: NSObject {
  4.  
  5. var content: String = "未开启" //倒计时要展示的内容
  6. var status: Bool = false //定时器状态
  7. private var timer: dispatch_source_t?
  8. private var currentQueue: dispatch_queue_t?
  9.  
  10. //这里使用了单利
  11. class func shareInstance() -> TimeCountdown {
  12. struct singleton {
  13. static var predicate: dispatch_once_t = 0
  14. static var instance: TimeCountdown? = nil
  15. }
  16. //只调用一次
  17. dispatch_once(&singleton.predicate,{ () -> Void in
  18. singleton.instance = TimeCountdown()
  19. })
  20. return singleton.instance!
  21. }
  22.  
  23. //调用该对象方法启动倒计时,minutes为传入的分钟数
  24. func startTimeOut(minutes: Int) {
  25. var timeOut = minutes * 60 //秒数,用于计算
  26. if timer != nil {
  27. dispatch_source_cancel(self.timer!)
  28. timer = nil;
  29. }
  30.  
  31. //不开启
  32. if (minutes == 0) {
  33. self.content = "未开启"
  34. self.status = false
  35. dispatch_async(dispatch_get_main_queue(),{ () -> Void in
  36. NSNotificationCenter.defaultCenter().postNotificationName("startTimeOut",object: nil,userInfo: nil)
  37. })
  38. return
  39. }
  40.  
  41. if currentQueue == nil {
  42. currentQueue = dispatch_queue_create("com.gcd.timeout",nil)
  43. }
  44. self.status = true
  45. timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,0,currentQueue)
  46. dispatch_source_set_timer(timer!,dispatch_walltime(nil,0),1*NSEC_PER_SEC,0)
  47. dispatch_source_set_event_handler(timer!,{ () -> Void in
  48. if (timeOut <= 0) {
  49. dispatch_source_cancel(self.timer!)
  50. self.content = "未开启"
  51. self.status = false
  52. dispatch_async(dispatch_get_main_queue(),{ () -> Void in
  53. //暂停播放器
  54. AudioPlayerViewController.pausePlayer()
  55. })
  56. } else {
  57. var minutes = timeOut / 60
  58. var seconds = timeOut % 60
  59. self.content = "\(minutes)分\(seconds)秒后,将暂停播放广播"
  60. --timeOut
  61. }
  62. dispatch_async(dispatch_get_main_queue(),{ () -> Void in
  63. //每秒发送一次通知,用于更新要显示的倒计时时间(在制定控制器监听该通知)
  64. NSNotificationCenter.defaultCenter().postNotificationName("startTimeOut",userInfo: nil)
  65. })
  66. })
  67. //启动 dispatch source
  68. dispatch_resume(timer!)
  69. }
  70.  
  71.  
  72.  
  73. }

猜你在找的Swift相关文章