ios - Firebase 实时数据库查询不起作用

标签 ios firebase firebase-realtime-database filter

我正在尝试检索一些值而不是其他值。事实上,我想通过用户的名字来搜索用户。

我尝试使用 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 开头,您还会得到以cd

您需要做的是以字符串开头的最高值结束,例如对于 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/

相关文章:

ios - 解析仪表板设置

ios - 从字典访问 FlutterStandardTypedData 时出现 "[__NSArrayI data]: unrecognized selector"

javascript - 使用 React 和 firereact 从 Firebase 中删除节点

firebase - firebase 部署时为 "Public Directory Warning - Public directory is empty"

python - 如何获取Firebase数据?

angular - 如何使用 RXJS 运算符根据重复值对 Firebase 可观察列表进行排序

ios - 在执行 SKAction moveTo 时跟踪 SKSpriteNode 的位置

ios - AVAudioEngine.connect 上的 CoreAudio 错误和崩溃

具有动态参数的 Angular Factory Provider

firebase - Firebase 实时数据库安全规则中的 auth.uid 和 auth.token.sub 有什么区别