Dismiss UIAlertView after 5 Seconds Swift
A solution to dismiss an alert automatically in Swift 3 and Swift 4 (Inspired by part of these answers: [1], [2], [3]):
// the alert viewlet alert = UIAlertController(title: "", message: "alert disappears after 5 seconds", preferredStyle: .alert)self.present(alert, animated: true, completion: nil)// change to desired number of seconds (in this case 5 seconds)let when = DispatchTime.now() + 5DispatchQueue.main.asyncAfter(deadline: when){ // your code with delay alert.dismiss(animated: true, completion: nil)}
Result:
You can dismiss your UIAlertView
after a 5 second delay programmatically, like so:
alert.show()// Delay the dismissal by 5 secondslet delay = 5.0 * Double(NSEC_PER_SEC)var time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))dispatch_after(time, dispatch_get_main_queue(), { alert.dismissWithClickedButtonIndex(-1, animated: true)})
in swift 2 you can do this. Credit to @Lyndsey Scott
let alertController = UIAlertController(title: "youTitle", message: "YourMessage", preferredStyle: .Alert) self.presentViewController(alertController, animated: true, completion: nil) let delay = 5.0 * Double(NSEC_PER_SEC) let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay)) dispatch_after(time, dispatch_get_main_queue(), { alertController.dismissViewControllerAnimated(true, completion: nil) })