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

时间:2018-02-28 21:17:38

标签: swift firebase random

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

因此,我需要有关如何在每次创建记录时创建序列号的信息,或者有人知道从数据库中检索随机记录的简单方法,这将非常有用。最好是快速的。

我的数据库结构:

database structure

2 个答案:

答案 0 :(得分:1)

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

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

if

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

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

一旦获得随机索引,您就可以创建一个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 
    }

}

答案 1 :(得分:0)

Database.database().reference().child("profiles").observeSingleEvent(of: .value) { (snapshot) in 
    if let snapshots = snapshot.children.allObjects as? [DataSnapshot] { 
        // do random number calculation
         let count = snapshots.count
         return snapshots[Int(arc4random_uniform(UInt32(count - 1)))]
}