Reputation: 1388
My application has a UILongPressGestureRecognizer
, which display an alert with UIAlertController
when the user touches two elements on the screen. Currently, the user must press the OK button in order to dismiss the alert, however I would like to dismiss the alert after 0.5 seconds automatically, so the user doesn't compromise his interaction with the app.
Is there any way to do that?
Upvotes: 10
Views: 8789
Reputation: 2091
Swift 5
Present UIAlertController
and in completion block, dismiss it after specified time.
By default, any code in completion block runs on a different thread so, get the main thread and dismiss UIAlertController
let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .alert)
present(alertController, animated: true) {
DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
alertController.dismiss(animated: true, completion: nil)
}
}
Upvotes: 3
Reputation: 147
let alert = UIAlertController(title: "Message Title", message: nil, preferredStyle: .alert)
present(alert, animated: true) {
sleep(1)
alert.dismiss(animated: true, completion: nil)
}
Upvotes: -2
Reputation: 385
Swift 3:
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
alert.dismiss(animated: false, completion: nil)
}
Upvotes: 2
Reputation: 3239
I have a custom function updated for Swift 2.1 which uses a UIAlertController to simulate the Toast functionality in Android.
func showToast(withMessage message:String) {
let menu = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet)
let cancel = UIAlertAction(title: message, style: .Cancel, handler: nil)
menu.addAction(cancel)
self.presentViewController(menu, animated: true, completion: nil)
let delay = 1.5 * Double(NSEC_PER_SEC)
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
self.tableView.setEditing(false, animated: true)
dispatch_after(time, dispatch_get_main_queue()) { () -> Void in
self.dismissViewControllerAnimated(true, completion: nil)
}
}
This shows a complete, working solution for the OP.
Upvotes: 5
Reputation: 5470
You can achieve the automatic dismiss of alert view by using dispatch_after of GCD.
Try below code :
let delay = 0.5 * Double(NSEC_PER_SEC)
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
dispatch_after(time, dispatch_get_main_queue()) { () -> Void in
self.dismissPopover()
}
Here, dismissCategoryPopover()
is a custom method that will be called automatically after 0.5 seconds to dismiss the alert view.
Upvotes: 9