由于在另一个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)
}
}
}
如何在我的情况下正确显示警报。...
答案 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
方法的showAlert
在viewController
层次结构中当前未显示view
,因此您应该在其中获取最新显示的viewController
view
层次结构,或尝试在rootViewController
上展示。
您可以选中this以获得当前显示的viewController
。
答案 1 :(得分:1)
只需使用
self.navigationController?.popToRootViewController(animated: false)
或
self.navigationController?.setViewControllers([LoginViewController], animated: true)
代替
self.navigationController?.viewControllers.removeAll()