I am trying to have a helper class that represents a UIAlertController . Since this is a helper class, I want it to work regardless of the hierarchy of views and without information about it. I can show a warning, but when it is fired, the application crashed into:
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Trying to dismiss UIAlertController <UIAlertController: 0x135d70d80> with unknown presenter.'
I am creating a popup using:
guard let window = UIApplication.shared.keyWindow else { return } let view = UIView() view.isUserInteractionEnabled = true window.insertSubview(view, at: 0) window.bringSubview(toFront: view) // add full screen constraints to view ... let controller = UIAlertController( title: "confirm deletion?", message: ":)", preferredStyle: .alert ) let deleteAction = UIAlertAction( title: "yes", style: .destructive, handler: { _ in DispatchQueue.main.async { view.removeFromSuperview() completion() } } ) controller.addAction(deleteAction) view.insertSubview(controller.view, at: 0) view.bringSubview(toFront: controller.view) // add centering constraints to controller.view ...
When I click yes , the application crashes and the handler does not hit before the crash. I can’t imagine the UIAlertController because it will depend on the current view hierarchy, while I want the popup to be independent
EDIT: quick fix Thanks to @Vlad for this idea. It seems that working in a separate window is much easier. So here is a working Swift solution:
class Popup { private var alertWindow: UIWindow static var shared = Popup() init() { alertWindow = UIWindow(frame: UIScreen.main.bounds) alertWindow.rootViewController = UIViewController() alertWindow.windowLevel = UIWindowLevelAlert + 1 alertWindow.makeKeyAndVisible() alertWindow.isHidden = true } private func show(completion: @escaping ((Bool) -> Void)) { let controller = UIAlertController( title: "Want to do it?", message: "message", preferredStyle: .alert ) let yesAction = UIAlertAction( title: "Yes", style: .default, handler: { _ in DispatchQueue.main.async { self.alertWindow.isHidden = true completion(true) } }) let noAction = UIAlertAction( title: "Not now", style: .destructive, handler: { _ in DispatchQueue.main.async { self.alertWindow.isHidden = true completion(false) } }) controller.addAction(noAction) controller.addAction(yesAction) self.alertWindow.isHidden = false alertWindow.rootViewController?.present(controller, animated: false) } }
ios swift popup crash
Guig
source share