Как я могу исправить попытку представить UIAlertController на ViewController, чье представление не находится в иерархии окон - PullRequest
0 голосов
/ 21 октября 2019

Я пытаюсь работать с оповещениями, чтобы показать возможные ошибки при входе в мое приложение. У меня есть несколько предупреждений в разных частях моего кода. Никто из них не работает. Они не отображаются и не печатаются:

Попытка представить, чей вид не находится в иерархии окон!

Я вижу много разных сообщений с одной и той же проблемойони все исправляются, если что-то сделать с viewDidAppear. Я пробовал это, но поскольку это не только одно предупреждение, а поскольку я использую функцию для вызова каждого предупреждения, эта помощь не сработала.

Вот код:

    func alerts(title: String, message: String) {
        let alert = UIAlertController(title:"Oops...", message: message, preferredStyle: UIAlertControllerStyle.alert)
        alert.addAction(UIAlertAction(title:"Ok", style: UIAlertActionStyle.default, handler: { (action) in
            alert.dismiss(animated: true, completion: nil)
        }))
        self.present(alert, animated: true, completion: nil)
    }

    @IBAction func loginPressed(_ sender: Any) {

        if emailField.text == "", pwField.text == "" {
            alerts(title: "Oops...", message: "Please fill out the fields.")
            accessGiven = false
        } else {
            accessGiven = true
        }

//        if emailField.text == "", pwField.text != "" || emailField.text != "", pwField.text == "" {
//            alerts(title: "Oops...", message: "Please fill out all fields.")
//            accessGiven = false
//        } else {
//            accessGiven = true
//        }

        Auth.auth().fetchProviders(forEmail: self.emailField.text!, completion: { (stringArray, error) in
            if error != nil {
                print(error!)
                self.alerts(title: "Oops...", message: "Something went wrong, please try again")
                self.accessGiven = false
            } else {
                if stringArray == nil {
                    print("No active account using this email.")
                    self.alerts(title: "Oops...", message: "There is no active account using this E-Mail.")
                    self.accessGiven = false
                    //self.performSegue(withIdentifier: "segue.SignUp.toTabBar", sender: nil)

                } else {
                    print("There is an active account using this E-mail")
                    self.accessGiven = true
                }
            }
        })

        Auth.auth().signIn(withEmail: emailField.text!, password: pwField.text!) { (user, error) in

            if let error = error {
                print(error.localizedDescription)
                self.alerts(title: "Oops...", message: "Something went wrong, please try again")
                self.accessGiven = false
            } else {
                self.accessGiven = true
            }
            if let user = user {

            }
        }
        if accessGiven == true {
            self.performSegue(withIdentifier: "segue.LogIn.toTabBar", sender: nil)
        }

    }

1 Ответ

0 голосов
/ 21 октября 2019

Если значение accessGiven равно true, вы выполняете переход к другому viewController. И поэтому ваш текущий viewController больше не является частью иерархии окон. А затем вы пытаетесь представить контроллеры оповещений из блоков завершения ваших fetchProviders и signIn , используя self.present(alert, animated: true, completion: nil), где self - это ваш viewController, который больше не является частью иерархии окон. Вот почему ошибка выбрасывается. Чтобы убедиться, просто закомментируйте свой executeSegue и попробуйте тот же код. Надеюсь, это поможет.

...