【问题标题】:Attempt to present alertcontroller whose view is not in window hierarchy尝试显示视图不在窗口层次结构中的警报控制器
【发布时间】:2017-11-04 14:34:48
【问题描述】:

我在 Swift 3 中遇到以下错误:

Attempt to present alertcontroller whose view is not in window hierarchy

我已经参考了有关此主题的其他帖子,但无济于事。更具体地说,我已经实现了这篇文章中建议的更改:AlertController is not in the window hierarchy

我仍然收到同样的错误。

我所做的是:

  1. 创建一个 AlertHelper.swift 助手类:

    class AlertHelper {
    

    func showAlert(fromController 控制器: UIViewController) { let alert = UIAlertController(title: "Please Try Again", message: "Email Already In Use", preferredStyle: .alert) controller.present(警报,动画:真,完成:无) } }

  2. 在我的视图控制器中,在按下按钮时调用的函数下,我检查用户输入的电子邮件地址是否已存储在我的 Firebase 数据库中,如果是,我尝试显示“来自 AlertHelper 类的电子邮件已在使用中的警报:

    Auth.auth().createUser(withEmail: email, password: password) { (user, error)     in
            if error != nil {
                if let errCode = AuthErrorCode(rawValue: error!._code) {
                    switch errCode {
                    case .emailAlreadyInUse:
                        let alert = AlertHelper()
                        alert.showAlert(fromController: self)
                        return
                    default:
                        print("other error")
                    }
                }
            }
            else {
                // Inputs user email into database
                self.ref.child("Users").child((user?.uid)!).setValue(["Email": email, "Location": ""])
                self.performSegue(withIdentifier: "todorm", sender: self)
            }
        }
    

数据库的东西有效,唯一没有出现的是警报。有任何想法吗?谢谢!!

【问题讨论】:

    标签: xcode uiviewcontroller swift3 uialertcontroller


    【解决方案1】:

    将警报子类化为单独的类是一种奇怪的做法。

    你应该尝试在你的 ViewController 类中创建一个方法

    func showAlert() { 
       let alert = UIAlertController(title: "Please Try Again", message: "Email Already In Use", preferredStyle: .alert) 
       self.present(alert, animated: true, completion: nil)
    }
    

    调用方法使用:

    self.showAlert()
    

    【讨论】:

    • 我也尝试过这种方法,但我仍然得到相同的 UIAlertController not in window hierarchy 错误。奇怪的是:当我尝试在一个简单的 if-else 语句中显示警报时,它起作用了。但是,当我尝试在嵌套在另一个函数调用中的 if 语句中显示警报时(如上所示),我得到了错误。
    • 检查 createUser 方法是否创建了控制器实例。它可能会在现有控制器之上显示一个新控制器,因此当您尝试在现有控制器上显示时,会发生错误。
    • 我怀疑是这种情况。如果是这样,我将如何解决它?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多