加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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!)
    }



}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读