gpt4 book ai didi

swift - 如何使用顺序 ID 从 Firebase 检索随机对象?

转载 作者:行者123 更新时间:2023-11-28 14:59:39 31 4
gpt4 key购买 nike

我正在寻找一种简单的方法来使用 swift 在 firebase 中查询我的数据库以检索随机对象。我已经阅读了很多线程,但似乎没有简单的方法。一个例子表明可以通过创建一个序号来完成,但是没有关于如何为每条记录创建这个序号的信息。

因此,要么我需要有关每次创建记录时如何创建序列号的信息,要么如果有人知道从数据库中检索随机记录的简单方法,这将非常有帮助。最好 swift 。

我的数据库结构:

database structure

最佳答案

在 Firebase 中查询随机对象<非常简单的解决方案>SWIFT 4

您可以尝试的一件事是像这样重组您的数据:

    - profiles
- 1jon2jbn1ojb3pn231 //Auto-generated id from firebase.
- jack@hotmail.com
- oi12y3o12h3oi12uy3 //Auto-generated id from firebase.
- susan@hotmail.com
- ...

Firebase 的自动生成的 ID 在发送到 Firebase 时按键的字典顺序排序,因此您可以轻松地创建这样的函数:

    func createRandomIndexForFirebase() -> String {
let randomIndexArray = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","0","1","2","3","4","5","6","7","8","9"]`
let randomIndex = Int.random(in: 0..<randomIndexArray.endIndex)

//In lexicographical order 'A' != 'a' so we use some clever logic to randomize the case of any letter that is chosen.
//If a numeric character is chosen, .capitalized will fail silently.
return (randomIndex % 2 == 0) ? randomIndexArray[randomIndex] : randomIndexArray[randomIndex].capitalized
}

获得随机索引后,您可以创建一个 firebase 查询来获取随机配置文件。

    var ref: DatabaseReference? = Database.database().reference(fromURL: "<DatabaseURL>")
ref?.child("profiles").queryOrderedByKey().queryStarting(atValue: createRandomIndexForFirebase()).queryLimited(toFirst: 1).observeSingleEvent(of: .value, with: { snapshot in
//Use a for-loop in case you want to set .queryLimited(toFirst: ) to some higher value.
for snap in snapshot.children {
guard let randomProfile = snap as? DataSnapshot else { return }
//Do something with your random profiles :)
}

关于swift - 如何使用顺序 ID 从 Firebase 检索随机对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49038712/

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