我有一个注册类,其中包含3个用户名,电子邮件和密码的文本字段。当用户点击“注册”按钮时,将调用handleRegister()
函数。此函数从这些textfields.text中获取三个值,并将它们发送到子节点下的Firebase数据库,其中包含用户ID,如下图所示:
我的问题是我希望能够更新注册类外面的任何3个值(电子邮件,名称,密码)。我该怎么做到这一点?谢谢。在这里注册我的代码:
func handleRegister() {
guard let email = emailTextField.text, let password = passwordTextField.text, let name = usernameTextField.text else {
return
}
FIRAuth.auth()?.createUser(withEmail: email, password: password, completion: { (user: FIRUser?, error) in
if error != nil {
return
}
guard let uid = user?.uid else {
return
}
//successfully registered user.
let imageName = NSUUID().uuidString
let storageRef = FIRStorage.storage().reference().child("profile_images").child("\(imageName).png")
if let uploadData = UIImagePNGRepresentation(self.profileImageView.image!) {
storageRef.put(uploadData, metadata: nil, completion: { (metadata, error) in
if error != nil {
return
}
if let profileImageUrl = metadata?.downloadURL()?.absoluteString {
let values = ["name": name, "email": email, "password": password, "profileImageUrl": profileImageUrl]
self.registerUserIntoDatabaseWithUID(uid: uid, values: values as [String : AnyObject])
}
})
}
})
}
private func registerUserIntoDatabaseWithUID(uid: String, values: [String: AnyObject]) {
let ref = FIRDatabase.database().reference()
let usersReference = ref.child("users").child(uid)
usersReference.updateChildValues(values, withCompletionBlock: { (err, ref) in
if err != nil {
return
}
print("Successfully saved user to database.")
self.dismiss(animated: true, completion: nil)
})
}
答案 0 :(得分:2)
您有两种选择:
选项1:您需要在某处保存用户的数据库ID,以便稍后在应用程序中使用它来处理这种情况。您可以将ID保存在Userdefaults或其他更安全的地方。
选项2:您可以使用Auth.auth()来检索登录用户的ID?currentUser?.uid
guard let uid = Auth.auth()?.currentUser?.uid else { return }
如果您拥有此ID,则可以像在registerUserIntoDatabaseWithUID()
中一样更新数据库中的值。
func updateEmailAddress(text: String) {
guard let uid = Auth.auth()?.currentUser?.uid else { return }
let userReference = Database.database().reference.child("users/(uid)")
let values = ["email": text]
// Update the "email" value in the database for the logged in user
userReference.updateChildValues(values, withCompletionBlock: { (error, ref) in
if error != nil {
print(error.localizedDescription)
return
}
print("Successfully saved user to database.")
self.dismiss(animated: true, completion: nil)
})
}
答案 1 :(得分:1)
Nota Bene
如果您对此答案有任何疑问,请添加评论。 这和其他答案之间的区别在于我 指明如何根据要求更新多个位置。
您希望了解使用数据扇出方法。它涉及在多个位置写入数据。这是一个快速代码示例:
let key = ref.child("posts").childByAutoId().key
let post = ["uid": userID,
"author": username,
"title": title,
"body": body]
let childUpdates = ["/posts/\(key)": post,
"/user-posts/\(userID)/\(key)/": post]
ref.updateChildValues(childUpdates)
要了解有关此方法的更多信息,请参阅以下文档: https://firebase.google.com/docs/database/ios/read-and-write#update_specific_fields