显示模特

时间:2016-09-25 23:21:40

标签: ios swift model-view-controller firebase

我试图从Firebase后端向我的用户显示错误提醒。

我根据MVC分离了我的注册函数并将其放入模型中,但是print(error!.localizedDescription)嵌套在我的模型中的if statement中。我不能简单地制作alertController,因为它不属于main.storyboard中的视图。

如何从我的模型中提取该错误并通过VC将其显示回视图?

MODEL

func signUp(email: String, username: String, password: String, data: NSData!)
{

    FIRAuth.auth()?.createUser(withEmail: email, password: password, completion: { (user, error) in
        if error == nil
        {

        self.setUserInfo(user: user, username: username, password: password, data: data)

        }
        else
        {
        print(error!.localizedDescription)
        }
    })
}

查看控制器

@IBAction func signupButton(_ sender: AnyObject)
    {   
    if self.emailTextField.text == "" || self.usernameTextField.text == "" || self.passwordTextField.text == ""

    {
        let alertController = UIAlertController(title: "Oops!", message: "Please enter a valid username, email & password", preferredStyle: .alert)
        let defaultAction = UIAlertAction(title: "Ok", style: .cancel, handler: nil)
        alertController.addAction(defaultAction)

        self.present(alertController, animated: true, completion: nil)
    }
    else
    {
    let data = UIImageJPEGRepresentation(self.userProfilePicture.image!, 0.8)

    networkingService.signUp(email: emailTextField.text!, username: usernameTextField.text!, password: passwordTextField.text!, data: data as NSData!)
    }
}

NetworkingService是我调用的结构。

感谢您的帮助,我仍然试图围绕MVC。

1 个答案:

答案 0 :(得分:2)

在模型的signUp方法中添加完成块。

func signUp(email: String, username: String, password: String, data: NSData, completion: Error? -> ())
{
    FIRAuth.auth()?.createUser(withEmail: email, password: password, completion: { (user, error) in
        if error == nil {
            self.setUserInfo(user: user, username: username, password: password, data: data)
        }
        completion(error)
    })
}

然后提供一个闭包,当用户未被创建时将调用该闭包。

@IBAction func signupButton(_ sender: AnyObject) {

    guard
        let email = emailTextField.text,
        let username = usernameTextField.text,
        let password = passwordTextField.text,
        let image = userProfilePicture.image,
        let data = UIImageJPEGRepresentation(image, 0.8)
    where
        email != "" &&
        username != "" &&
        password != ""
    else {
        let alertController = UIAlertController(title: "Oops!", message: "Please enter a valid username, email & password", preferredStyle: .alert)
        alertController.addAction(UIAlertAction(title: "Ok", style: .cancel, handler: nil))
        present(alertController, animated: true, completion: nil)
    }

    networkingService.signUp(email: email, username: username, password: password, data: data) { error in
        if let error = error {
            print(error.localizedDescription)
        }
    }
}