如何检查Firebase中是否存在密钥?我看过这个链接here,但它适用于Firebase 3,它对我的情况并不起作用。因此,对于我的情况,我想检查是否存在用户名,如果存在,则不要注册用户,但如果没有,则注册。我有类似的东西:
let usersDB = Database.database().reference().child("Users")
var taken = false
usersDB.observeSingleEvent(of: .value, with: { (snapshot) in
if snapshot.hasChild(username) {
taken = true
self.errorLabel.text = "Username already taken."
}
})
if !taken {
// Email registration
Auth.auth().createUser(withEmail: email, password: password, completion: { (user, error) in
if error != nil {
print(error!.localizedDescription)
self.errorLabel.text = error!.localizedDescription
} else {
// Allows for username log in
usersDB.child(username).setValue(["email" : user?.email])
self.performSegue(withIdentifier: "goToGroups", sender: self)
}
})
}
observeSingleEvent
是之前类似帖子的解决方案,但它仅在我在此行usersDB.child(username).setValue(["email" : user?.email])
上添加子项后才会运行,之前从未运行过。还有其他办法吗?
答案 0 :(得分:9)
这看起来像是处理异步调用的问题。在if !taken
返回数据之前很可能会检查observeSingleEvent
,因为它是异步的,因此其余代码将继续运行。一种选择是将if !taken
移动到闭包中,如下所示:
let usersDB = Database.database().reference().child("Users/\(username)")
var taken = false
usersDB.observeSingleEvent(of: .value, with: { (snapshot) in
if snapshot.exists() {
taken = true
self.errorLabel.text = "Username already taken."
}
if !taken {
// Email registration
Auth.auth().createUser(withEmail: email, password: password, completion: { (user, error) in
if error != nil {
print(error!.localizedDescription)
self.errorLabel.text = error!.localizedDescription
} else {
// Allows for username log in
usersDB.child(username).setValue(["email" : user?.email])
self.performSegue(withIdentifier: "goToGroups", sender: self)
}
})
}
})