警告:尝试在<App name:>上显示<UIAlertController:>,其视图不在窗口层次结构中

时间:2019-07-25 05:53:35

标签: ios swift xcode cocoa-touch alert

由于在另一个VC中显示警报而出现此错误,但是如何解决此问题。

我的代码是:

{
     let message = res[0]["message"] as! String
     //If session expaired move to login page
     if message == "Session Expired" {
         //Session Expired
         DispatchQueue.main.async {
             //Remove all navigations
             self.navigationController?.viewControllers.removeAll()
             //Check whether the user logined or not
             UserDefaults.standard.set(false, forKey: "isUserLoggedIn")
             //Clear user defaults
             SharedClass.sharedInstance.clearDataFromUserDefaults()

             let lvc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "LVC") as! LoginViewController
             let appDelegate = UIApplication.shared.delegate as! AppDelegate
             appDelegate.window?.rootViewController = lvc
         }
     }
     //Call alert function
     self.showAlert(title: "", msg: message)
 }

警报功能:

//Alert function
extension UIViewController {
    func showAlert(title: String, msg: String) {
        DispatchQueue.main.async {
            let alert = UIAlertController(title: title, message: msg, preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
            self.present(alert, animated: true, completion: nil)
        }
    }
}

如何在我的情况下正确显示警报。...

2 个答案:

答案 0 :(得分:1)

尝试将alertController上的rootViewController呈现为

extension UIViewController {
    func showAlert(title: String, msg: String) {
        DispatchQueue.main.async {
            let alert = UIAlertController(title: title, message: msg, preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
            (UIApplication.shared.delegate as! AppDelegate).window?.rootViewController?.present(alert, animated: true, completion: nil)
        }
    }
}

您正在调用viewController方法的showAlertviewController层次结构中当前未显示view,因此您应该在其中获取最新显示的viewController view层次结构,或尝试在rootViewController上展示。

您可以选中this以获得当前显示的viewController

答案 1 :(得分:1)

只需使用

self.navigationController?.popToRootViewController(animated: false)

 self.navigationController?.setViewControllers([LoginViewController], animated: true)

代替

self.navigationController?.viewControllers.removeAll()