I've created a UIAlertView that contains a UIActivityIndicator. Everything works great, but I'd also like the UIAlertView to disappear after 5 seconds.
How can I Dismiss my UIAlertView after 5 seconds?
var alert: UIAlertView = UIAlertView(title: "Loading", message: "Please wait...", delegate: nil, cancelButtonTitle: "Cancel"); var loadingIndicator: UIActivityIndicatorView = UIActivityIndicatorView(frame: CGRectMake(50, 10, 37, 37)) as UIActivityIndicatorView loadingIndicator.center = self.view.center; loadingIndicator.hidesWhenStopped = true loadingIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray loadingIndicator.startAnimating(); alert.setValue(loadingIndicator, forKey: "accessoryView") loadingIndicator.startAnimating() alert.show()
A solution to dismiss an alert automatically in Swift 3 and Swift 4 (Inspired by part of these answers: [1], [2], [3]):
// the alert view let 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() + 5 DispatchQueue.main.asyncAfter(deadline: when){ // your code with delay alert.dismiss(animated: true, completion: nil) }
Result:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With