Automatically disabling UIAlertController

My application has a UILongPressGestureRecognizer that displays a warning with a UIAlertController when a user touches two items on the screen. Currently, the user must click OK to cancel the warning, however I would like to turn off the notification automatically after 0.5 seconds, so the user does not jeopardize his interaction with the application.

Is there any way to do this?

+6
source share
3 answers

You can automatically turn off viewing alerts using the dispatch_after GCD.

Try entering the 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 reject the alert.

+7
source

I have a custom function updated for Swift 2.1 that uses the UIAlertController to simulate the Toast function 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) } } 

It features a complete working solution for the OP.

+3
source

Swift 3:

 DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { alert.dismiss(animated: false, completion: nil) } 
0
source

Source: https://habr.com/ru/post/978816/


All Articles