如何使用顺序ID从Firebase检索随机对象? [英] How do I retrieve a random object from Firebase using a sequential ID?

查看:98
本文介绍了如何使用顺序ID从Firebase检索随机对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm looking for an easy way to query my database in firebase using swift to retrieve a random object. I've read a lot of threads and there doesn't seem to be an easy way. One example showed it can be done be creating a sequential number but there's no information on how to create this sequential number for each record.

因此,或者我需要有关每次创建记录时如何创建序号的信息,或者是否有人知道一种从数据库中检索随机记录的简便方法,这将非常有帮助.最好迅速.

So either I need information on how to create a sequential number each time a record is created or if someone knows an easy way to retrieve a random record from a database that would be very helpful. In swift preferably.

我的数据库结构:

推荐答案

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

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

One thing that you could try is to restructure your data like this:

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

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

Firebase's auto-generated id's are sorted in lexicographical order by key, when they are sent to Firebase, so you can easily create a function like this:

    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查询来获取随机配置文件.

Once you get a random index you can create a firebase query to grab a random profile.

    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 :)
    }

}

这篇关于如何使用顺序ID从Firebase检索随机对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆