See the main code directly
//Due Date LetEndDate = Datepicker.date//Start date LetStartDate = Date ()//time interval LetTimeinterval:timeinterval = Enddate.timeintervalsince (startdate)ifTimer = = Nil {//Time remainingvar timeout = TimeIntervalifTimeout! =0{//Create global queue LetQueue = Dispatchqueue.global ()//Create a time source under the global queueTimer = Dispatchsource.maketimersource (flags: [], Queue:queue)//Set cycle interval is one second and start immediatelyA timer? Schedulerepeating (WallDeadline:DispatchWallTime.now (), Interval:. Seconds (1))//Time source departure eventA timer? setEventHandler (handler: {//must be the date of the current date and also be restricted on the DatePicker ifTimeout <=0{ Self. Timer?. Cancel () Self. Timer = Nil DispatchQueue.main.async (execute: { Self. Day.text ="XX" Self. Hour.text ="XX" Self. Minute.text ="XX" Self. Second.text ="XX"}) }Else{//Calculate remaining time LetDays = INT (timeout)/(3600* -)ifDays = =0{ Self. Day.text =""} LetHours = (int (timeout)-Int (days) * -*3600) /3600 Letminutes = (int (timeout)-Int (days) * -*3600-Int (Hours) *3600) / - Letseconds = Int (timeout)-Int (days) * -*3600-Int (Hours) *3600-Int (minutes) * - //Refresh UI in main queueDispatchQueue.main.async (execute: {ifDays = =0{ Self. Day.text ="0"}Else{ Self. Day.text ="\ (days)"}ifHours <Ten{ Self. Hour.text ="0"+"\ (Hours)"}Else{ Self. Hour.text ="\ (Hours)"}ifMinutes <Ten{ Self. Minute.text ="0"+"\ (minutes)"}Else{ Self. Minute.text ="\ (minutes)"}ifSeconds <Ten{ Self. Second.text ="0"+"\ (seconds)"}Else{ Self. Second.text ="\ (seconds)"}}) Timeout-=1} })//Start time sourceA timer? Resume ()}}
DEMO
DEMO
Swift3.0 GCD timer Use, achieve countdown, uidatepicker use, imitation write a countdown to the activity of the demo