I\'ve created a UIAlertView that contains a UIActivityIndicator. Everything works great, but I\'d also like the UIAlertView to disappear after 5 seconds.
Ho
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:
Create the alert object as a global variable.
You can use a NSTimer
for this purpose.
var timer = NSTimer.scheduledTimerWithTimeInterval(5.0, target: self, selector: Selector("dismissAlert"), userInfo: nil, repeats: false)
func dismissAlert()
{
// Dismiss the alert from here
alertView.dismissWithClickedButtonIndex(0, animated: true)
}
NOTE:
Important: UIAlertView is deprecated in iOS 8. (Note that UIAlertViewDelegate is also deprecated.) To create and manage alerts in iOS 8 and later, instead use UIAlertController with a preferredStyle of UIAlertControllerStyleAlert.
Reference : UIAlertView
For swift 4 you can use this code
let alertController = UIAlertController(title:"Alert",message:nil,preferredStyle:.alert)
self.present(alertController,animated:true,completion:{Timer.scheduledTimer(withTimeInterval: 5, repeats:false, block: {_ in
self.dismiss(animated: true, completion: nil)
})}
I'm not an expert but this works for me and I guess is easier
let alert = UIAlertController(title: "", message: "YOUR MESSAGE", preferredStyle: .alert)
present(alert, animated: true) {
sleep(5)
alert.dismiss(animated: true)
}