【问题标题】:Check if username already exist's : Swift, Firebase检查用户名是否已经存在:Swift、Firebase
【发布时间】:2016-09-21 05:06:18
【问题描述】:

我正在尝试检查用户名是否存在。当我调用queryOrderedBychild 时,快照值始终可用,但它会打印出我的整个数据库,而不仅仅是我请求queryOrderby 的数据。当我调用queryEqualToValue 时,它总是返回null。我已经尝试了很多方法来弄清楚。

这是我的代码:

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"]
    }
  }
}

【问题讨论】:

  • 您的 UsersRef 是什么?我的猜测是,在这种情况下,它链接到用户 id (g50X0FvEsSO4L457v7NzS3dAABl1),而 Nickname 不是它的直接孩子,所以它永远不会找到它,因为它没有搜索正确的位置。当我经历这个时,我还记得在搜索子节点时遇到了 .value 的问题,我相信我使用了 .ChildAdded 和 .ChildChanged 。

标签: ios swift firebase firebase-realtime-database


【解决方案1】:

修改您的 JSON 树以包含一个单独的节点 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的didChangeEditing事件中(为了更好的用户体验!)

【讨论】:

  • 对不起,我睡了一整天。我很疲倦。我有很多关于 Firebase 的问题需要问。不能在这里发布所有问题。我可以通过电子邮件或 Facebook 与您联系,我可以联系到您。非常感谢!!!
  • @KhôiVNguyễn 这不是 stackoverflow 的工作方式。如果您有好的问题,请将它们带到这里。在大多数用户在线的时间写您的问题,通常是美国东部标准时间上午 11 点到下午 4 点。并希望你能得到答案。或者可能在之前的答案中找到您问题的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-28
  • 2023-03-22
  • 1970-01-01
  • 1970-01-01
  • 2016-07-26
相关资源
最近更新 更多