I am firing a UIAlertController with a timeout using the extension. Here is the code.
extension UIViewController { func dismissViewController(timer: Timer) { let viewController = timer.userInfo as! UIViewController if (viewController.isViewLoaded && (viewController.view.window != nil)) { viewController.dismiss(animated: true, completion: nil) } } func presentWithTOT(_ viewControllerToPresent: UIViewController, timeout: Double) { if (timeout != 0.0) { Timer.scheduledTimer(timeInterval: timeout, target: self, selector: #selector(dismissViewController), userInfo: viewControllerToPresent, repeats: false) } present(viewControllerToPresent, animated: true, completion: nil) } } func myfunc() { let alertController = UIAlertController(...) presentWithTOT(alertController, timeout: 2.0) }
One note for the above code is that the timer has a strong link to alertController, which means the object will not be released before the timeout expires.
source share