【问题标题】:Attempt to present UIAlertController whose view is not in the window hierarchy尝试呈现其视图不在窗口层次结构中的 UIAlertController
【发布时间】:2018-06-06 03:25:27
【问题描述】:

更具体地说,我得到的错误警告是:

Attempt to present UIAlertController whose view is not in the window hierarchy!

我目前正在创建一个注册页面,要求用户填写一些具体的详细信息,例如姓名、国家、电子邮件、密码等。为了确保用户提供所有相关信息,我正在尝试编写代码来发送警报如果用户没有提供所有信息。我已经编写了从 stakeoverflow 获得帮助的代码。

问题:每当用户将任何字段留空时,它都不会显示警报,并且默认情况下会执行将用户带到登录页面的 segue。这是我第一次创建警报,因此不要出什么问题(我相信我 95% 的代码都已到位)

谁能帮忙?

     @IBAction func signUpPressed(_ sender: Any) {

    if nameText.text!.isEmpty || genderText.text!.isEmpty || countryText.text!.isEmpty || yourSchool.text!.isEmpty || yourClass.text!.isEmpty {

        print("Please fill all fields") 

        //my code is printing above error in the Xcode console but the below code is not working 

        //setting error message if not all fiels filled
        let alertController = UIAlertController(title: "Error", message: "Please fill all fields", preferredStyle: .alert)

        let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
        alertController.addAction(defaultAction)

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

    }

    else {

        Auth.auth().createUser(withEmail: yourEmail.text!, password: yourPassword.text!) { (user, error) in

            if error != nil {

                ///print errror message
                let alertController = UIAlertController(title: "Error", message: error?.localizedDescription, preferredStyle: .alert)

                let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
                alertController.addAction(defaultAction)

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

            } else {

                print("You have successfully signed up")

                self.performSegue(withIdentifier: "JoinUs2SignPage", sender: self)

                //updating user information
                let userID = Auth.auth().currentUser!.uid
                let usertype: String = "Student"
                self.ref.child("users").child(userID).setValue(["usertype": usertype ,"username": self.nameText.text!, "usergender": self.genderText.text!, "usercountry": self.countryText.text!, "userschool": self.yourSchool.text!, "userclass": self.yourClass.text!,])
            }
        }
    }

【问题讨论】:

  • 你用断点测试过这个吗?我的意思是没有其他代码做同样的事情或执行 segue 的故事板连接?
  • 为什么yourSchool.text被检查了两次?
  • @vadish 在这里两次不会出问题
  • @Sh_Khan 和 == "".isEmpty 没有区别。
  • @vadian swift 有问题

标签: ios swift xcode uialertcontroller uialertaction


【解决方案1】:

动作可能超出主线程

  DispatchQueue.main.async {

  ///print errror message
   let alertController = UIAlertController(title: "Error",    message: error?.localizedDescription, preferredStyle: .alert)

   let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
   alertController.addAction(defaultAction)

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


}

试试这个方法

检查这样的空白

 let nameTrimmed = self.nameText.text?.trimmingCharacters(in: .whitespacesAndNewlines)

 let genderTrimmed = self.genderText.text?.trimmingCharacters(in: .whitespacesAndNewlines)

 let countryTrimmed = self.countryText.text?.trimmingCharacters(in: .whitespacesAndNewlines)

 let schoolTrimmed = self.schoolText.text?.trimmingCharacters(in: .whitespacesAndNewlines)



 if  nameTrimmed.text == "" ||  genderTrimmed.text == "" ||   countryTrimmed.text == "" ||  schoolTrimmed.text == "" 

【讨论】:

  • 我猜文本字段的默认值为“”。所以它不会把它当作空的,这种方法可能行不通。
  • 嗨 Sh_Khan,我的代码能够在条件完全正常的情况下执行,因为它能够打印错误,即打印(“请填写所有字段”)。但是,代码的 UIAlert 部分不起作用,即没有弹出警报消息
  • @Sh_Khan 感谢您的解决方案,但它不起作用
【解决方案2】:
@IBAction func registerPressed(_ sender: Any) {

    if nameText.text!.isEmpty || genderText.text!.isEmpty || countryText.text!.isEmpty || yourSchool.text!.isEmpty || yourClass.text!.isEmpty {

        print("Please fill all fields") //my code is printing this error

        //alert message popup

        let alertController = UIAlertController(title: "Error", message: "Please fill all fields", preferredStyle: .alert)
        alertController.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action:UIAlertAction) in
        print("Okay")
        }))

        let alertWindow = UIWindow(frame: UIScreen.main.bounds)
        alertWindow.rootViewController = UIViewController()
        alertWindow.windowLevel = UIWindowLevelAlert
        alertWindow.makeKeyAndVisible()
        alertWindow.rootViewController?.present(alertController, animated: true, completion: nil)


    }

    else {

        Auth.auth().createUser(withEmail: yourEmail.text!, password: yourPassword.text!) { (user, error) in

                    if error != nil {

                        ///print errror message

                        let alertController = UIAlertController(title: "Error", message: error?.localizedDescription, preferredStyle: .alert)
                        alertController.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action:UIAlertAction) in
                            print("Okay")
                        }))

                        let alertWindow = UIWindow(frame: UIScreen.main.bounds)
                        alertWindow.rootViewController = UIViewController()
                        alertWindow.windowLevel = UIWindowLevelAlert + 1;
                        alertWindow.makeKeyAndVisible()
                        alertWindow.rootViewController?.present(alertController, animated: true, completion: nil)

                    }

                    else {

                        print("You have successfully signed up")

                        self.performSegue(withIdentifier: "JoinUs2SignPage", sender: self)

                        //updating user information
                        let userID = Auth.auth().currentUser!.uid
                        let usertype: String = "Student"
                        self.ref.child("users").child(userID).setValue(["usertype": usertype ,"username": self.nameText.text!, "usergender": self.genderText.text!, "usercountry": self.countryText.text!, "userschool": self.yourSchool.text!, "userclass": self.yourClass.text!,])
                        }
            }
        }

}

【讨论】:

    猜你喜欢
    • 2023-03-31
    • 2017-07-27
    • 2020-08-07
    • 2016-11-29
    • 1970-01-01
    • 2015-06-04
    • 1970-01-01
    • 2014-06-01
    • 1970-01-01
    相关资源
    最近更新 更多