【发布时间】:2018-07-26 18:36:23
【问题描述】:
我有一个注册视图控制器,它调用 Service 类并使用其 static func signUp(...) 将某人注册到数据库。
如果注册不成功,应通过showAlert(...) 静态方法显示警报。
但是,正在发生的事情是记录了不成功的注册,但我当前的方法没有显示警报。
Attempt to present <UIAlertController: xx> on <Yyy:SignUpViewController: ss> whose view is not in the window hierarchy!
目前,我正在尝试将 SignUpViewController 作为参数 (vc: UIViewController) 传递给静态方法,然后调用 Service.showAlert(on: vc, ...)。
我还尝试将showAlert(...) 方法合并到SignUpViewController 类中作为extension UIViewController,并从Service signUp() 作为vc.showAlert(...) 调用它。我收到与上述相同的错误。
重要的是,我想将代码重用于来自不同视图控制器的数据库调用,因此我不想重写代码并将其放置在每个视图控制器中。这不仅仅是为了注册。我希望在外部类中调用这些数据库。
代码:
服务类
static func signUp(email: String, password: String, vc: UIViewController) {
Auth.auth().signIn(withEmail: email, password: password) { (authResult, error) in
if let error = error {
print("Failed to sign in with error ", error)
Service.showAlert(on: vc, style: .alert, title: "Sign-in Error", message: error.localizedDescription)
return
}
// ...code
}
// ...code
}
// other methods
static func showAlert(on: UIViewController, style: UIAlertControllerStyle, title: String?, message: String?, actions: [UIAlertAction] = [UIAlertAction(title: "Ok", style: .default, handler: nil)], completion: (() -> Swift.Void)? = nil) {
let alert = UIAlertController(title: title, message: message, preferredStyle: style)
for action in actions {
alert.addAction(action)
}
on.present(alert, animated: true, completion: completion)
}
SignUpViewController 类方法调用
Service.signUp(email: emailTextField.text!, password: passwordTextField.text!, vc: self)
编辑:
如果我从 SignUpViewController 中执行登录功能,则会显示警报:
@IBAction func btnActionLogin(_ sender: Any) {
Auth.auth().createUser(withEmail: self.emailTextField.text!, password: self.passwordTextField.text!) { (authResult, error) in
if let error = error {
print("Failed to create new user with error ", error)
Service.showAlert(on: self, style: .alert, title: "Account Creation Error", message: error.localizedDescription)
return
} else {
// ... more code
}
}
编辑 2:
我实施的方法实际上很好。是我在错误的地方执行切换视图控制器!我不小心切换了视图控制器,暗示登录成功,即使它没有成功。
【问题讨论】:
标签: ios swift uiviewcontroller uialertcontroller