Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dismiss UIAlertView after 5 Seconds Swift

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() 
like image 919
Serge Pedroza Avatar asked Dec 23 '14 04:12

Serge Pedroza


1 Answers

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:

enter image description here

like image 158
ronatory Avatar answered Sep 30 '22 17:09

ronatory