swift gcd 定时器。获取验证码

来源:互联网 发布:linux 远程执行命令 编辑:程序博客网 时间:2024/05/21 10:21

 //获取验证码

    func getCodeButtonTouch(sender:UIButton) {

        //在获取期间不允许点击

        sender.backgroundColor =UIColor.gray

        sender.isUserInteractionEnabled =false

        

        var count =60;

        let timer =DispatchSource.makeTimerSource()


        timer.setEventHandler {

            count -= 1

            DispatchQueue.main.async {

                self.codeBtn?.setTitle("获取(\(count)s)", for: UIControlState.normal)

            }

        }

        timer.setCancelHandler {

            DispatchQueue.main.async {

                self.codeBtn?.isUserInteractionEnabled = true

                self.codeBtn?.backgroundColor =MAIN_COLOR

                self.codeBtn?.setTitle("获取(60s)", for: UIControlState.normal)

            }

        }

        //间隔总时间 60

        timer.scheduleRepeating(deadline: .now(), interval: .seconds(1), leeway: .milliseconds(60))

        timer.resume()

        //59秒时执行

        DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(59), execute:{

            timer.cancel()

        })

        //获取验证码

        getCodeRequest()

        //收起键盘

        self.view.endEditing(true)

        

    }