2

I would like to include UIAlertController in my SwiftUI project because I have more customization options with UIAlertController than with swiftui alert. I've already partially done that with this code:

struct CustomAlertManager {
    
    static let shared = CustomAlertManager()
    
    private init() {}
    
    func showAlert() {
        let alert = UIAlertController(title: "Achtung", message: "Sie werden weiter geleitet", preferredStyle: .alert)
        let okAction = UIAlertAction(title: "Ok", style: .default) { action in
            
        }
        alert.addAction(okAction)
        
        if let controller = UIApplication.shared.rootViewController {
            controller.present(alert, animated: true)
        }
    }
}

My UIApplication extension:

extension UIApplication {
    var rootViewController: UIViewController? {
        let scene = self.connectedScenes.first(where: { $0.activationState == .foregroundActive }) as? UIWindowScene

        return scene?.keyWindow?.rootViewController
    }
}

But now to my problem: This works pretty much fine but when I want to present an UIAlertController inside of a sheet the alert is not displayed (maybe its is unter the sheet). Note: No, the controller (UIApplication.shared.rootViewController) is not empty, so the .present(_:) method will be called 👍. Best regards!

5
  • Do you get any error messages in the console? Commented Apr 12, 2022 at 22:19
  • This is a known thing it isn't a bug both the sheet and the Alert are being presented in the same spot in the rootViewController. Don't use rootViewController if you need a UIViewController create one yourself and use UIViewControllerRepresentable Commented Apr 13, 2022 at 0:06
  • @loremipsum I thought so too. Thanks! Commented Apr 13, 2022 at 9:05
  • @burnsi no...... Commented Apr 13, 2022 at 9:05
  • The rootViewController is a common thing people offer as a solution around here but it is just a shortcut/bandaid. Apple has changed the way to access it with every iteration of SwiftUI I don’t think they want people to use it as a rule. Commented Apr 13, 2022 at 10:58

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.