2016-09-25 75 views
0
的提醒

我想從Firebase後端向我的用戶顯示錯誤提醒。顯示來自Model

我根據MVC分開我的註冊功能,並把它放在模型中,但print(error!.localizedDescription)嵌套在我的模型中的if statement。我不能簡單地製作一個alertController,因爲它不屬於main.storyboard中的視圖。

如何從我的模型中提取該錯誤並通過VC將其顯示回視圖?

模型

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的頭。

回答

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) 
     } 
    } 
} 
+0

完美的工作!謝謝! – ishkur88