gpt4 book ai didi

ios - Swift Firebase -.queryStarting(atValue :) and . queryEnding(atValue:) 返回所有子项

转载 作者:行者123 更新时间:2023-11-29 05:51:59 25 4
gpt4 key购买 nike

当我查询特定的子项时,我会返回所有结果,而不是特定于我要查找的结果:

例如,如果我的搜索文本以字母“c”开头,我应该只从下面得到猫和牛,但由于某种原因,我也得到了公牛。

root
|
@---users
|
@---uid_1000
| |--uid: "uid_1000"
| |--username: "bull"
|
@---uid_2000
| |--uid: "uid_2000"
| |--username: "cat"
|
@---uid_3000
|--uid: "uid_3000"
|--username: "cow"

我在想也许问题是因为我似乎捕获了用户节点(复数字典)上的所有内容,然后循环遍历可能是问题的字典,但后来我意识到它仍然应该只是以字母“c”应该出现在字典中开始,并且 bull 应该被跳过。

我哪里出错了?

let searchText = "c"

let ref = Database.database().reference().child("users")
.queryOrdered(byChild: "username")
.queryStarting(atValue: searchText)
.queryEnding(atValue: searchText + "\u{f8ff}")

ref?.observeSingleEvent(of: .value, with: { (snapshot) in

if !snapshot.exists() { return }

// dictionaries plural
guard let dictionaries = snapshot.value as? [String: Any] else { return }

dictionaries.forEach({ (key, value) in

guard let dict = value as? [String: Any] else { return }
let user = User(dict: dict)

let isContained = self.users.contains(where: { (containedUser) -> Bool in
return user.uid == containedUser.uid
})

if !isContained {
self.users.append(user)
self.collectionView.reloadData()
}
})

根据 Frank 的请求使用 Json 进行更新:

{
"users" : {
"1000" : {
"userId" : "1000",
"username" : "bull"
},
"2000" : {
"userId" : "2000",
"username" : "cat"
},
"3000" : {
"userId" : "3000",
"username" : "cow"
}
}
}

匹配的图片。我从 json 中排除了其他 2 个对象,因为即使它们出现在我这边(我实际上得到了 5 个结果),我只想关注问题中的前 3 个对象。

enter image description here

最佳答案

我刚刚尝试了这段代码:

let ref = Database.database().reference(withPath: "55574954")
ref.child("users") .queryOrdered(byChild: "username") .queryStarting(atValue: "c") .queryEnding(atValue: "d").observeSingleEvent(of: .value, with: { (snapshot) in
for child in (snapshot.children.allObjects as! [DataSnapshot]) {
print(child.key)
}
})

在此数据结构上:

{
"users" : {
"1000" : {
"userId" : "1000",
"username" : "bull"
},
"2000" : {
"userId" : "2000",
"username" : "cat"
},
"3000" : {
"userId" : "3000",
"username" : "cow"
}
}
}

实时 JSON 为 here .

运行此代码会打印:

2000

3000

这正是我对上面的数据结构所期望的。

关于ios - Swift Firebase -.queryStarting(atValue :) and . queryEnding(atValue:) 返回所有子项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55574954/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com