Swift 4:Firebase即使出错也仍在创建用户?

时间:2018-01-16 21:07:27

标签: swift firebase firebase-authentication swift4

我有一个按下注册按钮时运行的功能,如果用户没有帐户,或者没有错误,则使用Auth.auth().createUser(withEmail: email, password: password)注册用户。然后我将它们添加到数据库中并对其进行签名。如果有任何错误,我会显示错误并return

但是,即使用户之前从未注册过并且数据库没有其信息,我也会收到.emailAlreadyInUse错误,之后无论如何都会将用户添加到数据库中。 Firebase似乎正在创建帐户,然后给我一个错误。为什么这样,我该如何解决?

这是我的代码:

@IBAction func registerPressed(_ sender: Any?) {

        //set up new user using Firebase
        if (firstNameTextField.text! == "" && emailTextField.text! == "" && passwordTextField.text! == "") {
            self.topMessage.text = "Please enter your details"
        } else if (firstNameTextField.text! == "" && emailTextField.text! != "" && passwordTextField.text! != "") {
            self.topMessage.text = "Please enter your first name"
        } else {
            Auth.auth().createUser(withEmail: emailTextField.text!, password: passwordTextField.text!) {
                (user, error) in
                if error != nil {
                    print(error!)
                    if let errCode = AuthErrorCode(rawValue: error!._code) {
                        switch errCode {
                        case .weakPassword:
                            self.topMessage.text = "Password too short"
                            break
                        case .emailAlreadyInUse:
                            self.topMessage.text = "Email already in use"
                            break
                        case .invalidEmail:
                            self.topMessage.text = "Invalid email"
                            break
                        case .missingEmail:
                            self.topMessage.text = "Please enter an email"
                            break
                        default:
                            self.topMessage.text = "Error :( Please try again!"
                            break
                        }
                    }
                    return
                }
                else if let user = user {

                    let username = self.firstNameTextField.text!
                    let name = self.firstNameTextField.text!
                    let email = self.emailTextField.text!
                    let profileImage = ""
                    let password = self.passwordTextField.text!

                    let newUser = User(uid: user.uid, username: username, name: name, profileImage: profileImage, email: email, userCoins: 0, questsComplete: 0, rewardsRedeemed: 0, streak: 0, isSubscribed: false)

                    newUser.save(completion: { (error) in
                        if error != nil {
                            print(error!)
                        } else {
                            //successfully initialised
                            Auth.auth().signIn(withEmail: email, password: password, completion: { (user, error) in
                                if let error = error {
                                    print(error)
                                } else {
                                    self.performSegue(withIdentifier: "registerToMainMap", sender: self)
                                }
                            })

                        }
                    })

                }

            }
        }
    }

2 个答案:

答案 0 :(得分:0)

根据文件Firebase documentation on errors

  

FIRAuthErrorCodeEmailAlreadyInUse 表示用于尝试注册的电子邮件已存在。调用 fetchProvidersForEmail 来检查用户使用的登录机制,并提示用户使用其中一个登录。

那么,这样的事情会给你带来什么?

Auth.auth().fetchProviders(forEmail: emailTextField.text!) { (email,completion) in
   print("email is ", email!)
   print("completion is ", completion!)
}

答案 1 :(得分:0)

弄清楚我的问题。 .save()函数中嵌入了.saveProfileImage(),它在用户注册时运行。当我以不同的方式实现图像时,我评论了该功能。但是,由于.saveProfileImage()是一个completion(error),它也被注释掉了,因此func save(completion: @escaping (Error?) -> Void) {}无效。我只是把它变成func save()来修复它。

这是旧的save()功能:

func save(completion: @escaping (Error?) -> Void) {

        let ref = AppDatabaseReference.users(uid: uid).reference()
        ref.setValue(toDictionary())

        //save the user's profile image
        if let profileImage = self.profileImage {
            let firImage = FirebaseImage(image: profileImage)
            firImage.saveProfileImage(uid, { (error) in
                //called when profile image is successfully uploaded
                completion(error)
            })
        }
    }

.saveProfileImage()

func saveProfileImage(_ userUID: String, _ completion: @escaping (Error?) -> Void) {

        let resizedImage = image.resize()
        if let imageData = UIImageJPEGRepresentation(resizedImage, 0.9) {
            //get the reference
            ref = AppStorageReference.profileImages.reference().child(userUID)
            downloadURLString = ref.description

            //save data to reference
            ref.putData(imageData, metadata: nil, completion: { (metaData, error) in
                completion(error)
            })
        }

    }

以及注册后保存用户的内容:

else if let user = user {

                    let username = self.firstNameTextField.text!
                    let name = self.firstNameTextField.text!
                    let email = self.emailTextField.text!
                    let profileImage = ""
                    let password = self.passwordTextField.text!

                    let newUser = User(uid: user.uid, username: username, name: name, profileImage: profileImage, email: email, userCoins: 0, questsComplete: 0, rewardsRedeemed: 0, streak: 0, isSubscribed: false)

                    newUser.save(completion: { (error) in
                        if error != nil {
                            print(error!)
                        } else {
                            //successfully initialised
                            Auth.auth().signIn(withEmail: email, password: password, completion: { (user, error) in
                                if error != nil {
                                    print(error!)
                                } else {
                                    print("segue to perform")
                                    self.performSegue(withIdentifier: "registerToMainMap", sender: self)
                                }
                            })

                        }
                    })

                }

save()

func save() {
  let ref = AppDatabaseReference.users(uid: uid).reference()
  ref.setValue(toDictionary())
}

保存用户:

else if let user = user {

                    let username = self.firstNameTextField.text!
                    let name = self.firstNameTextField.text!
                    let email = self.emailTextField.text!
                    let profileImage = ""
                    let password = self.passwordTextField.text!

                    let newUser = User(uid: user.uid, username: username, name: name, profileImage: profileImage, email: email, userCoins: 0, questsComplete: 0, rewardsRedeemed: 0, streak: 0, isSubscribed: false)

                    newUser.save()
                    //successfully initialised
                    Auth.auth().signIn(withEmail: email, password: password, completion: { (user, error) in
                        if error != nil {
                            print(error!)
                        } else {
                            print("segue to perform")
                            self.performSegue(withIdentifier: "registerToMainMap", sender: self)
                        }
                    })

                }