gpt4 book ai didi

swift - 我如何修复在 View 不在窗口层次结构中的 ViewController 上呈现 UIAlertController 的尝试

转载 作者:行者123 更新时间:2023-11-30 10:33:56 25 4
gpt4 key购买 nike

我正在尝试使用警报作为登录我的应用程序时显示潜在错误的一种方式。我的代码的不同部分有几个警报。它们都不起作用。它们不显示和打印:

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

我看到很多不同的帖子都有同样的问题,它们都通过使用 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)
}

}

最佳答案

如果您的accessGiven值为true,则您正在执行segue到不同的viewController。因此您当前的 viewController 不再是窗口层次结构的一部分。然后,您尝试使用 self.present(alert, animated: true, completion: nil) 从您的 fetchProviderssignIn 函数的completionBlocks 中呈现警报 Controller 。其中 self 是您的 viewController,它不再是窗口层次结构的一部分。这就是抛出错误的原因。为了确保这一点,只需注释您的 PerformSegue 并尝试相同的代码。希望对您有所帮助。

关于swift - 我如何修复在 View 不在窗口层次结构中的 ViewController 上呈现 UIAlertController 的尝试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58491035/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com