Search code examples
swiftdelayuialertcontroller

Countdown in UIAlertController


I would like to countdown 3 seconds in my alert controller. Not sure how to do this. I can get the alert to disappear in 3 seconds, just the countdown is missing.

//simple alert dialog
let alertController = UIAlertController(title: "Workflow successful", message: "Modified reminder's priority or list.", preferredStyle: .Alert)

var secs = 3
let defaultAction = UIAlertAction(title: "Dismiss in " + secs, style: .Default, handler: nil)
alertController.addAction(defaultAction)

dispatch_async(dispatch_get_main_queue()) {
    //self.presentViewController(alertController, animated: true, completion: nil)
    self.showViewController(alertController, sender: self)
}

let delayTime = dispatch_time(DISPATCH_TIME_NOW,
              Int64(secs * Double(NSEC_PER_SEC)))
dispatch_after(delayTime, dispatch_get_main_queue()) {
    alertController.dismissViewControllerAnimated(true, completion: nil)
}

Solution

  • After you set the delay time to dismiss your view controller, you can set a timer to call a function after a second like:

    var timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(self.decrease), userInfo: nil, repeats: true)
    
    func decrease()
    {
        self.secs-=1
        self.defaultAction.setValue("Dismiss in \(self.secs)", forKey: "title")
    }
    

    And it will update the title with your new time.