Search code examples
ioswindowsuialertcontrollerswift5

Present UIAlertView on window


There are possibility that, there is custom view over my controller and on which I have to show alert. So I am using below extension to present controllers on window rather than on any UIViewController.

Extension

extension UIViewController {
    func presentControllerToWindow(){
        let win = UIWindow(frame: UIScreen.main.bounds)
        let vc = UIViewController()
        vc.view.backgroundColor = .clear
        win.rootViewController = vc
        win.windowLevel = UIWindow.Level.alert + 1
        win.makeKeyAndVisible()
        vc.present(self, animated: true, completion: nil)
    }
}

Present AlertController

let alertController = UIAlertController(title: nil, message: "Select Option", preferredStyle: .alert)

alertController.presentControllerToWindow()

Issue :

The code is working fine upto swift 4.X but in swift 5.X, alert controller appears and dismissed automatically on the other second.

GIF:

  1. OpenPicker adds custom view as a subview.
  2. On clicking add file, I am presenting alertcontroller.
  3. Its automatically dismissed.

enter image description here

Edit :

I am adding my custom view like below.

extension UIView {

    func addToWindow()  {
        let window = UIApplication.shared.keyWindow!
        self.frame = window.bounds
        window.makeKeyAndVisible()
        window.windowLevel = window.windowLevel + 1
        window.addSubview(self)
    }
}

let customView = MyCustomView()
customView.addToWindow()

Now over this MyCustomView, I need to show UIAlertController


Solution

  • you have to add your UIViewController view in UIApplication keyWindow

    extension UIViewController {
        func presentControllerToWindow(){
            let win = UIWindow(frame: UIScreen.main.bounds)
            let vc = UIViewController()
            vc.view.backgroundColor = .clear
            win.rootViewController = vc
            win.windowLevel = UIWindow.Level.alert + 1
            win.makeKeyAndVisible()
            UIApplication.shared.keyWindow?.addSubview(vc.view) //added
            vc.present(self, animated: true, completion: nil)
        }
    }