【问题标题】:How do I get Firebase to add new users and not overwrite current users (iOS, Xcode 8)?如何让 Firebase 添加新用户而不覆盖当前用户(iOS、Xcode 8)?
【发布时间】:2017-09-12 03:43:53
【问题描述】:

此代码在创建新用户后不断覆盖数据库。这是我输入的代码:

func handleRegister() {
    guard let email = emailTextField.text, let password = passwordTextField.text, let name = nameTextField.text
        else {
            print("Form is not Valid")
            return
        }

    Auth.auth().createUser(withEmail: email, password: password, completion: {(user: User?, error) in
        if error != nil {
            print(Error.self)
            return
        }

        guard (user?.uid) != nil else { return }
    })

    let ref = Database.database().reference(fromURL: "//Firebase link")
    let usersReference = ref.child("Users").child("uid")
    let values = ["name": name, "email": email]

    usersReference.updateChildValues(values, withCompletionBlock: { (err, ref) in
        if err != nil {
            print(err.self)
            return
        }
        print("Successfully saved user in Firebase DB")
    })
}

我觉得我错过了一些非常简单的东西。任何帮助,将不胜感激。

【问题讨论】:

  • 让 usersReference = ref.child("Users").child("uid") 静态提供帮助?您需要通过当前的帮助,或者您可以每次都选择唯一密钥,这样数据就不会被替换
  • 我该怎么做?我在帖子中尝试了每个人的建议,唯一有效的是不断替换数据的方法。
  • 检查我编辑的答案,它将逐步清除

标签: ios swift firebase firebase-realtime-database xcode8


【解决方案1】:

编辑: 在你的

之后
guard (user?.uid) != nil else {
  return
}

把你剩下的代码放在它下面:

let ref = Database.database()... //your code
//put inside the completion block of create user
//the rest of your code up to the updateChildValues

并在 users

中将此 uid 用作您孩子的参数

所以它会变成:

let usersReference = ref.child("Users").child(uid)

注意 uid 没有用双引号括起来

您必须将其放在 createUser 完成块中,因为您的 user?.uid 的范围仅取决于该块。

【讨论】:

  • 我将代码更改为您在上面放置的代码,出于某种奇怪的原因,Xcode 想要将保护 let 更改回我之前的那个。在我这样做之后,当我从 .child(uid) 中去掉双引号时,Xcode 会抛出一个错误,提示“使用未解析的标识符”。如果有帮助,我已将所有 Firebase 模块导入到项目中。
  • 哦,我的错。守卫让的范围仅限于您创建用户的完成块。尝试将您的代码块从“ref”变量移动到创建用户完成块内的 updateChildValues
  • 我编辑了我的答案。让我知道您是否感到困惑。
  • 好的,我会试一试。我今天还有其他事情要做,所以我会告诉你进展如何。
【解决方案2】:

每次运行时在代码中使用下面的代码,因为您提供静态“uid”,因此处理程序数据被替换,使用下面的代码添加一个具有当前用户 uid 的节点,该节点在 firebase DB 中创建帐户时分配给用户

//before viewDidLoad declare a global databaseRef as

let  databaseRef = Database.Database().reference //this will be used as base reference In all handlers 
var name : String = ""
var Uid : String = ""
var email : String = ""
var nameString : String = ""

func createUser(){
    Auth.auth().createUser(withEmail: self.EmailTextField.text!, password: self.PasswordTextField.text!) { (user, error) in

        if error == nil {
            print("You have successfully signed up")
            //Goes to the Setup page which lets the user take a photo for their profile picture and also chose a username

            self.nameString = self.nameTextField.text!

            self.AddUserDetails()

            DispatchQueue.main.async(execute: {
                let vc = self.storyboard?.instantiateViewController(withIdentifier: "Main")
                self.present(vc!, animated: true, completion: nil)
            })

        } else {
                 //this block shows error if exist
                 let alertController = UIAlertController(title: "Error", message: error?.localizedDescription, preferredStyle: .alert)

            let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
            alertController.addAction(defaultAction)

            self.present(alertController, animated: true, completion: nil)
            //this is my activity indicator
            self.spinnerView.isHidden = true
            self.spinner.isHidden = true
            self.spinner.stopAnimating()
        }
    }
}

func AddUserDetails(){
    //I make use of user nsobject class to get all details
    //you can also make use of some global strings
    self.name = self.nameString //name string store current display name
    //name string contains name which I am taking as input when a user want to sign up as a textField text
    self.email = (Auth.auth().currentUser?.email)! //current email
    self.Uid = (Auth.auth().currentUser?.uid)! //current uid


    let user:[String : AnyObject] = ["email": self.email as AnyObject,"name":self.name as AnyObject,"uID":self.Uid as AnyObject]

    databaseRef.child("users").child(self.Uid).setValue(user)

}

【讨论】:

  • 这个有帮助,但是当我输入代码时,我有 8 个错误。代码的上半部分从“func createUser()”到“self.present(alertController, animated: true, completion: nil)”除此之外,我一直到“databaseRef.child”都有错误无法弄清楚我做错了什么......
  • 请查看我编辑的答案并告诉我是否仍然存在一些错误,如果仍然存在,请告诉我哪一行给你错误
  • 我会尝试一下,让你知道会发生什么。可能要到今天晚些时候。感谢您的帮助!
  • 是的,如果存在问题,请告诉我,我会尝试解决。
【解决方案3】:

您没有调用您的代码在用户创建回调中写入数据库。因此它使用旧的 uid 创建用户引用,从而覆盖这些值。

 Auth.auth().createUser(withEmail: email, password: password, completion: {(user: User?, error) in

        if error != nil {
        print(Error.self)

        return
    }
// after this you are sure user created and now move your calls here 
//to write in firebase database.
    guard (user?.uid) != nil else {
        return
    }
})

【讨论】:

    猜你喜欢
    • 2012-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-15
    • 2019-02-10
    • 1970-01-01
    相关资源
    最近更新 更多