gpt4 book ai didi

swift - 如何从不同的类更新我的 Firebase 数据库中的值?

转载 作者:搜寻专家 更新时间:2023-10-31 22:29:50 26 4
gpt4 key购买 nike

我有一个注册类,其中包含 3 个文本字段,分别用于用户名、电子邮件和密码。当用户点击“注册”按钮时,将调用 handleRegister() 函数。此函数从这些 textfields.text 中获取三个值,并将它们发送到子节点下的我的 Firebase 数据库,其中包含它们的用户 ID,如下图所示:

enter image description here

我的问题是我希望能够在注册类之外更新这些值中的任意 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)
})
}

最佳答案

你有两个选择:

选项 1:您需要将用户的数据库 ID 保存在某个地方,以便稍后在应用程序中使用它来处理这种情况。您可以将 ID 保存在您的 Userdefaults 或其他更安全的地方。

选项 2:您可以使用 Auth.auth()?.currentUser?.uid 检索登录用户的 ID

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

关于swift - 如何从不同的类更新我的 Firebase 数据库中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40790723/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com