检查用户名是否已经存在:Swift、Firebase [英] Check if username already exist's : Swift, Firebase
问题描述
我正在尝试检查用户名是否存在.当我调用 queryOrderedBychild
时,快照值始终可用,但它会打印我的整个数据库,而不仅仅是我请求 queryOrderby
的数据.当我调用 queryEqualToValue
时,它总是返回 null.我尝试了很多方法来解决这个问题.
I'm trying to check if a username exists or not. When I call queryOrderedBychild
, snapshot value is always available but it will print down the whole database of mine, not just the data which I request queryOrderby
. When I call queryEqualToValue
, it always return null. I've tried many ways to figure it out.
这是我的代码:
DataService.instance.UsersRef.queryOrdered(byChild:"Nickname").queryEqual(toValue: "kai1004pro").observe(.value, with: { (snapshot) in
if (snapshot.value is NSNull) {
print("not found")
} else {
print("found")
print(snapshot.value)
}
})
这是我的 json 树:
This is my json tree:
Optional({
g50X0FvEsSO4L457v7NzS3dAABl1 = {
"User Profile" = {
Birthday = "Sep 20, 1992";
Gender = Female;
Nickname = kai1004pro;
UserUID = g50X0FvEsSO4L457v7NzS3dAABl1;
emailAddress = "poqksbs@gmail.con";
isFollow = 0;
isFriend = 0;
};
};
})
这是安全规则:
"rules": {
".read": true,
".write": "auth != null",
"Users": {
".read": true,
".write": "auth != null",
".indexOn": ["Nickname", "User Profile"]
}
}
}
推荐答案
修改您的 JSON 树以包含一个单独的节点 active_usernames
,以便在任何时候添加每个用户的用户名您创建新用户,每当您的用户修改其用户名时进行修改...
Modify your JSON tree to include a separate node active_usernames
, in that add username of every user whenever you create new user, modify whenever your user modify its username...
myApp:{
users:{
uid1:{....},
uid2:{....},
uid3:{....},
uid4:{....},
}
active_usernames :{
uid1username : "true",
uid2username : "true",
uid3username : "true",
uid4username : "true"
}
}
要检查您的用户名是否已经存在:-
To check your if username already exists:-
//Checking username existence
FIRDatabase.database().reference().child("active_usernames").child(self.enteredUsername.text!).observeSingleEvent(of: .value, with: {(usernameSnap) in
if usernameSnap.exists(){
//This username already exists
}else{
//Yippee!.. This can be my username
}
})
还要通过操纵安全规则,将您的安全规则更改为对所有人(ONLY READABLE)可读.
Also change your security rules to be readable (ONLY READABLE) to all, by manipulating the security rules.
{rules :{
active_usernames : {
".read" : "true",
".write" : "auth != null"
}
}
}
PS:- enteredUsername
是您输入用户名的文本字段.
PS:- enteredUsername
is the textField in which you enter your username.
建议:-将校验码保留在textField的didChangeEditing
事件中(为了更好的用户体验!)
Suggestion:- keep the checking code inside didChangeEditing
event of the textField(For better user experience.!)
这篇关于检查用户名是否已经存在:Swift、Firebase的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!