我正在尝试检索一些值而不是其他值。事实上,我想通过用户的名字来搜索用户。
我尝试使用 queryStarting(atValue: input)
和 queryEnding(atValue: "u{f8ff}")
但找不到正确的解决方案。
let input = searchInput.text?.lowercased()
print("Search for \(input!)")
let ref = Database.database().reference().child("Usernames").queryStarting(atValue: input).queryEnding(atValue: "u{f8ff}").queryOrderedByKey()
ref.observeSingleEvent(of: .value) { (snapshot) in
if snapshot.exists() {
for users in snapshot.children.allObjects as! [DataSnapshot] {
let user = users.value as? [String:AnyObject]
let id = user?["id"] as! String
Users.init(userId: (id))
print(users.key)
}
}
}
如您所见,我还添加了 queryOrderedByKey()
。如果我不添加该部分,它不会检索任何内容。
我想要的只是检索从我在文本字段中写入的内容开始的值。
Usernames
----- charles
----------id: charles's uid
----- pierre
----------id: pierre's uid
----- bob
----------id: bob's uid
----- lu
----------id: lu's uid
问题是,例如如果输入是“L”(搜索 lu),它会检索 [lu]。然后,如果输入是“Bo”(搜索 bob),它会检索 [lu] 和 [bob],而不仅仅是我想要的 [bob]。显然,如果输入是“C”(搜索 bob),它将检索 [lu]、[bob]、[pierre],最后检索 [charles]。
最佳答案
您当前的查询从正确的输入开始,但以 u{f8ff}
结束 - 这意味着如果您以 bo
开头,您还会得到以c
、d
等
您需要做的是以字符串开头的最高值结束,例如对于 bo
的输入,您希望以 bo\u{f8ff}
结尾。您可以通过将您的输入与该 unicode 值连接起来来完成此操作,即:
...queryEnding(atValue: input + "\u{f8ff}")... // <-- Also note that the unicode character is escaped here
关于ios - Firebase 实时数据库查询不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56228068/