[英]Firebase - how to get the key value in observeEventType = Value
[英]How to get the value of a key in firebase - iOS
这是我的JSON树的图像: 我的JSON TREE
问题:我想知道如何检查用户名(例如, 肖恩)是否存在于usernames
。 我目前不知道如何实现这一点。
我已经尝试过的: usernames
child的键是“ theUsernameOf- userUID
”,这会导致问题,因为userUID
是动态的并且与每个用户(从Firebase auth)不同,因此我不能使用:
.queryOrderedByChild("theUsernameOf-userUID").queryEqual(toValue: self.usernameTextBox.text!)
usernames
child的密钥不能像theUsername
一样是静态的,因为它只能具有1个值/不能生成更多节点。
非常感谢,对不起,如果我没有解释清楚。
我想修改您的数据库结构,因为当前的数据库结构不适合执行此查询。
它应该像下面这样:
始终对查询使用自动递增键。 usernames -> autoGeneratedKey -> yourData (Dictionary - Key-Value pair)
现在您可以轻松检查任何键的存在。
let ref = defaultDB.reference.child("usernames")
ref.queryOrdered(byChild: "username").queryEqual(toValue: "sean").observeSingleEvent(of: DataEventType.value) { (snapshot) in
if snapshot.exists() {
print("exists")
}
else {
print("doesn't exist")
}
}
输出:存在
这是正确的方法。 只需检查snapshot.exists()
为您完成工作。
这是你怎么做
将数据库引用设置为用户名节点。 例如db.ref.child("usernames")
现在使用for循环解析快照,让usernames = snapshot.value为! NSDictionary
现在for循环
for username in usernames{ if username.value == "Sean"{ // do whatever you want here } }
您还可以:
对usernames
进行firebase调用,然后执行以下操作:
let usernames = snapshot.value as? [String: AnyObject]
let usernames = snapshot.value as? [String: AnyObject]
,那么您所要做的就是
if let keyExists = usernames[YOURUSERNAMECHECKSTRING] { //It's true }
只是另一种看待方式。
当您在firebase中观察到任何引用时,您将获得DataSnapshot
作为回报。 快照具有children
枚举器属性,您可以在该属性上枚举每个子级。 每个孩子将是另一个DataSnapshot
。 现在,每个快照都有key
和value
。 您想要用户名吗? 它在value
属性中:
let databaseRef = Database.database().reference(withPath: "usernames")
databaseRef.observe(.value) { (snapshot) in
snapshot.children.forEach({ (child) in
if let child = child as? DataSnapshot, let value = child.value {
print(value) //"Sean", "Yuh"
// here you can check for your desired user
}
})
}
尝试此代码将帮助您无需更改Firebase结构
在斯威夫特
Database.database().reference(withPath: "users").queryOrdered(byChild: "usernames").queryEqual(toValue: "yourUserName").observe(.value) { (snapshot:DataSnapshot) in if snapshot.valueInExportFormat() is NSDictionary { // User is exits } else { } }
在目标c中
[[[[[FIRDatabase database] referenceWithPath:@"users"] queryOrderedByChild:@"usernames"] queryEqualToValue:@"your User Name"] observeSingleEventOfType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot * _Nonnull snapshot) { if ([snapshot.valueInExportFormat isKindOfClass:[NSDictionary class]]) { // User is exits } else { } }];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.