Home:ALL Converter>Present alert after dismissing View Controller

Present alert after dismissing View Controller

Ask Time:2020-06-12T21:00:15         Author:David

Json Formatter

I'm using the newest Xcode and Swift version.

I'm presenting a specific View Controller like this:

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let contactViewController = storyboard.instantiateViewController(identifier: "contactViewController")
show(contactViewController, sender: self)

I'm dismissing this View Controller like this:

self.presentingViewController?.dismiss(animated: true, completion: nil)

I want to present an UIAlertController right after dismissing the View Controller.

This:

self.presentingViewController?.dismiss(animated: true, completion: nil)

let alertMessage = UIAlertController(title: "Your message was sent", message: "", preferredStyle: .alert)
let alertButton = UIAlertAction(title: "Okay", style: UIAlertAction.Style.default)
alertMessage.addAction(alertButton)
self.present(alertMessage, animated: true, completion: nil)

… of course doesn't work because I cannot present an UIAlertController on a dismissed View Controller.

What's the best way to present this UIAlertController after the View Controller is dismissed?

Author:David,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/62344805/present-alert-after-dismissing-view-controller
Jawad Ali :

You can do it in completion handler by getting top controller like this\n\nself.presentingViewController?.dismiss(animated: true, completion: {\n let alertMessage = UIAlertController(title: \"Your message was sent\", message: \"\", preferredStyle: .alert)\n let alertButton = UIAlertAction(title: \"Okay\", style: UIAlertAction.Style.default)\n alertMessage.addAction(alertButton)\n UIApplication.getTopMostViewController()?.present(alertMessage, animated: true, completion: nil)\n })\n\n\nUsing this extension\n\nextension UIApplication {\n\n class func getTopMostViewController() -> UIViewController? {\n let keyWindow = UIApplication.shared.windows.filter {$0.isKeyWindow}.first\n if var topController = keyWindow?.rootViewController {\n while let presentedViewController = topController.presentedViewController {\n topController = presentedViewController\n }\n return topController\n } else {\n return nil\n }\n }\n}\n",
2020-06-12T13:20:54
yy