-2

In context of this question/answer I've attempted but the result is no alert presented.

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    
    
    let alertController = UIAlertController(title: "Error", message: "ABc", preferredStyle: UIAlertController.Style.alert)
    alertController.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
    
    let win = UIWindow(frame: UIScreen.main.bounds)
    let vc = UIViewController()
    vc.view.backgroundColor = .clear
    win.rootViewController = vc
    win.windowLevel = UIWindow.Level.alert + 1  // Swift 3-4: UIWindowLevelAlert + 1
    win.makeKeyAndVisible()
    vc.present(alertController, animated: true, completion: nil)

    return true
}

Attempt 2 based on the answer.

enter image description here

AppDeveloper
  • 1,816
  • 7
  • 24
  • 49

1 Answers1

2

Use below line:

self.window?.rootViewController?.present(alertController, animated: true, completion: nil)

Instead of

vc.present(alertController, animated: true, completion: nil)

than problem is solved.

Example:

DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5, execute: {
        let alertController = UIAlertController(title: "Alert Title", message:
          "Message", preferredStyle: .actionSheet)

        let okAction = UIAlertAction(title: "Ok", style:.default) {
            UIAlertAction in
            NSLog("OK Pressed")
        }

        let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) {
            UIAlertAction in
            NSLog("Cancel Pressed")
        }

        alertController.addAction(okAction)
        alertController.addAction(cancelAction)
        self.window?.rootViewController?.present(alertController, animated: true, completion: nil)
    })
Virani Vivek
  • 888
  • 1
  • 8
  • 22