gpt4 book ai didi

ios - 火力地堡 iOS : createUserWithEmail isn't generating userId (uid)

转载 作者:搜寻专家 更新时间:2023-11-01 07:22:16 27 4
gpt4 key购买 nike

我是 firebase 的新手,我正在尝试学习如何创建用户。我的问题是,当我通过按钮使用 createUserWithEmail 完成 block 时,出于某种原因,未生成唯一标识符 uid。这使我无法将关联的用户名和密码存储在 JSON 树中的 uid 下。我的代码如下(我使用“let databaseRef = FIRDatabase.database().reference()”在单独的 swift 文件中将 databaseRef 定义为全局常量)

@IBAction func createAccount(sender: AnyObject) {

var username = usernameField.text
var email = emailField.text
var password = passwordField.text
if username != "" && email != "" && password != "" {
FIRAuth.auth()?.createUserWithEmail(email!, password: password!, completion: { (user, error) in
databaseRef.child("users/(user.uid)/username").setValue(username)
databaseRef.child("users/(user.uid)/password").setValue(password)
databaseRef.child("users/(user.uid)/uid").setValue(user?.uid)
})
} else {
print("please complete all fields")
}
}

我知道没有生成 uid 有两个原因。首先,当我运行上面的代码并为我的每个文本字段输入值时,应用程序崩溃了。其次,如果我删除处理设置值的代码并将其替换为 print(user.uid),则返回 nil 值。我错过了什么?我可以理解uid是创建用户的一个非常重要的部分。

***这是我想出的解决方案

 @IBAction func createAccount(sender: AnyObject) {

var username = usernameField.text
var email = emailField.text
var password = passwordField.text

if username != "" && email != "" && password != "" {

FIRAuth.auth()?.createUserWithEmail(email!, password: password!, completion: { (user, error) in

if let user = FIRAuth.auth()?.currentUser {

databaseRef.child("users/\(user.uid)/username").setValue(username)
databaseRef.child("users/\(user.uid)/password").setValue(password)
databaseRef.child("users/\(user.uid)/email").setValue(email)

print(user.uid)

} else {

print("no user")

}

})


} else {

print("please complete all fields")

}

最佳答案

任何感兴趣的人的 Swift 4, 2018 解决方案:

Auth.auth().createUser(withEmail: email, password: password) { (user, error) in
// guard against errors and optionals
guard error == nil else { return }
guard let user = user else { return }
let userObject = [
"uid": user.uid,
"username": username,
"password": password, // I don't recommend storing passwords like this by the way
"email": email
] as [String:Any]
databaseRef.child("users").child(user.uid).setValue(userObject)
}

关于ios - 火力地堡 iOS : createUserWithEmail isn't generating userId (uid),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38213545/

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