【发布时间】:2017-06-24 19:26:34
【问题描述】:
我正在尝试查询我的 Firebase 数据库以查找具有特定名称或电子邮件地址的用户。我找到了几个如何做到这一点的示例,所有这些示例似乎都相对容易理解,但没有一个对我来说起到预期的作用。
这是我的 json 数据结构的示例。
{
"allUsers" : {
"uid0001" : {
"userInfo" : {
"email" : "firstName1.lastName1@email.com",
"firstName" : "firstName1",
"lastName" : "lastName1",
"uid" : "uid0001"
}
},
"uid0002" : {
"userInfo" : {
"email" : "firstName2.lastName2@email.com",
"firstName" : "firstName2",
"lastName" : "lastName2",
"uid" : "uid0002"
}
}
}
}
这是我尝试查询数据库的示例函数
func performQuery(forName queryText:String)
{
let key = "firstName"
let ref1 = firebaseDatabaseManager.allUsersRef.queryOrdered(byChild: queryText)
let ref2 = firebaseDatabaseManager.allUsersRef.queryEqual(toValue: queryText, childKey: key)
//ref.observeSingleEvent(of: .childAdded, with: {(snapshot) in
ref1.observe(.childAdded, with: {(snapshot) in
let userId = snapshot.key
if let dictionary = snapshot.value as? [String: AnyObject]
{
if let userInfo = dictionary["userInfo"] as? [String:AnyObject]
{
if
let email = userInfo["email"] as? String,
let firstName = userInfo["firstName"] as? String,
let lastName = userInfo["lastName"] as? String
{
let user = User.init(withFirst: firstName, last: lastName, userEmail: email, uid: userId)
}
}
}
})
}
你可以在这里看到我有两个例子来说明我如何构建 ref 和两个例子来说明我如何观察引用,尽管我已经尝试了我能想到的所有可能的组合。
如果我使用 ref.observe(.... 无论 queryText 是否实际存在,该块都将为节点上的所有用户执行。 如果我使用 ref.observeSingleEvent(of:.... 该块将为 json 结构中的最顶层用户执行。
除此之外,我还尝试了几种参考变体,它们什么都不返回。
感谢任何帮助! 谢谢
【问题讨论】:
标签: ios json swift firebase firebase-realtime-database