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:
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
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)
}
}