我正在尝试检查文本输入是否等于 firebase 数据库中的值。我遇到以下错误
"Snap (locations) null"
即使我输入一个我知道在数据库中的值。非常感谢您的帮助:-) 下面是我的 JSON 文件。
{
"locations" : {
"115 W Perry Carriage House" : {
"City" : "Savannah",
"State" : "GA",
"img" : " "
},
"115 W Perry Street" : {
"City" : "Savannah",
"State" : "GA",
"img" : " "
},
"117 West Charlton Street" : {
"City" : "Savannah",
"State" : "GA",
"img" : " "
},
"127 Coming Street Unit C" : {
"City" : "Charleston",
"State" : "SC",
"img" : " "
还有代码:
let databaseRef = Database.database().reference()
databaseRef.child("locations")
.queryOrdered(byChild: "locations")
.queryStarting(atValue: addressTextField.text)
.observe(DataEventType.value, with:
{
(snapshot) in
print(snapshot)
if snapshot.exists(){
print("Address is in DB")
}else{
print("Address doesn't exist")
}
})
}
最佳答案
您的问题中当前使用的代码查询正在查看嵌套在“locations”下的名为“locations”的子项的值。因此,如果您想象查询正在寻找数据,它会将第一个 child 拉到这里,而不是第二个,例如。
{
"locations" : {
"115 W Perry Carriage House" : {
"locations": "115 W Perry Carriage House", // <- here's one!
"City" : "Savannah",
"State" : "GA",
"img" : " "
},
"115 W Perry Street" : { // <- hmm...this one doesn't have "locations"
"City" : "Savannah",
"State" : "GA",
"img" : " "
},
//...
}
由于数据结构不包含任何名为“locations”的子项,因此任何值都不会与您要查找的值相匹配。由于您希望地址与 child 的 key 相匹配,因此我们无需查询即可获取该 child 的数据。我们可以观察确切的路径,像这样:
let databaseRef = Database.database().reference()
guard let text = addressTextField.text else { return }
databaseRef.child("locations/\(text)")
.observe(.value, with: { (snapshot) in
print(snapshot)
if snapshot.exists() {
print("Address is in DB")
} else {
print("Address doesn't exist")
}
})
关于ios - 检查 firebase 快照是否等于文本字段输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51529448/