ViewController reloads on presenting alert controller swift

73 Views Asked by At

I am working on project. i have added a simple alertController on clicking signup button. when i click on the button my viewcontroller reloads and then it shows that alertController. It is happening on iOS 13 and swift 5 or above

    let alert = UIAlertController(title: "Your title", message: "Your message", preferredStyle: .alert)

     let ok = UIAlertAction(title: "OK", style: .default, handler: { action in
     })
     alert.addAction(ok)
     let cancel = UIAlertAction(title: "Cancel", style: .default, handler: { action in
     })
     alert.addAction(cancel)
     DispatchQueue.main.async(execute: {
        self.present(alert, animated: true)
})
1

There are 1 best solutions below

0
Hasnain ahmad On BEST ANSWER

i resolved my problem by these lines of code

func alert(message: String, title: String = "") {
            let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
            let alertAction = UIAlertAction(title: "OK", style: .default) { (action) in
                print("Action")
            }
            alertController.addAction(alertAction)
           (UIApplication.shared.delegate as! AppDelegate).alertWindow.isHidden = true

            self.presentViewController(alertController: alertController)
    //        self.present(alertController, animated: true, completion:  nil)

        }
    func presentViewController(alertController: UIAlertController, completion: (() -> Void)? = nil) {
        if var topController = UIApplication.shared.keyWindow?.rootViewController {
            while let presentedViewController = topController.presentedViewController {
                topController = presentedViewController
            }

            DispatchQueue.main.async {
                topController.present(alertController, animated: true, completion: completion)
            }
        }
    }