我正在尝试检查用户名是否存在。当我打电话时queryOrderedBychild,快照值始终可用,但是它将打印我的整个数据库,而不仅仅是我请求的数据queryOrderby。当我打电话时queryEqualToValue,它总是返回null。我尝试了很多方法来解决。
queryOrderedBychild
queryOrderby
queryEqualToValue
这是我的代码:
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树:
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,即在您创建新用户时添加每个用户的用户名,在用户修改其用户名时进行修改…
active_usernames
myApp:{ users:{ uid1:{....}, uid2:{....}, uid3:{....}, uid4:{....}, } active_usernames :{ uid1username : "true", uid2username : "true", uid3username : "true", uid4username : "true" } }
要检查您的用户名是否已经存在:
//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 } })
通过操作安全规则,还可以将安全规则更改为所有人可读 (只读) 。
{rules :{ active_usernames : { ".read" : "true", ".write" : "auth != null" } } }
PS:- enteredUsername是您在其中输入用户名的textField。
enteredUsername
建议:- 将检查代码保留在 didChangeEditing textField事件的内部(以便获得更好的用户体验!!)
didChangeEditing