Skip to content

Instantly share code, notes, and snippets.

@harshvishu
Last active June 3, 2019 10:14
Show Gist options
  • Save harshvishu/b3ff27c32d7c9591b5036ae763dca26d to your computer and use it in GitHub Desktop.
Save harshvishu/b3ff27c32d7c9591b5036ae763dca26d to your computer and use it in GitHub Desktop.
public typealias CompletionHandler = () -> Void
class LiftOffViewController : UIViewController {
var countDownTimer: CountDown?
@IBOutlet weak var labelTimeLeft: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
countDownTimer = CountDownTimer(endsAfter: TimeInterval(10000), repeatingTask: countDownTimerRepeatingTask, completion: countDownTimerCompletion)
}
private var countDownTimerRepeatingTask: CompletionHandler? {
let handler: CompletionHandler = { [weak self] in
guard let `self` = self,
let countDownTimer = self.countDownTimer
else {return}
var timeRemaining: TimeInterval = (countDownTimer.timeLimit - countDownTimer.timeElapsed)
timeRemaining.round(.toNearestOrEven)
self.labelTimeLeft.text = "\(timeRemaining)"
}
return handler
}
private var countDownTimerCompletion: CompletionHandler? {
let handler: CompletionHandler = { [weak self] in
guard let `self` = self else {return}
let alert = UIAlertController(title: "Lift Off!", message: "Launch confirmed. Successful lift off!", preferredStyle:
.alert)
let okAction = UIAlertAction(title: "OK", style: .default) { (_ : UIAlertAction) -> Void in
}
alert.addAction(okAction)
self.present(alert, animated: true, completion: nil)
}
return handler
}
@IBAction func didTapRedButton(_ sender: UIButton) {
guard let timer = countDownTimer else {return}
if timer.isRunning {
timer.stop() // Stop if already running
} else {
timer.start() // Otherwise start the timer
}
}
deinit {
countDownTimer?.stop()
countDownTimer = nil
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment