【问题标题】:How do I retrieve a random object from Firebase using a sequential ID?如何使用顺序 ID 从 Firebase 检索随机对象?
【发布时间】:2018-02-28 21:17:38
【问题描述】:

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

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

我的数据库结构:

【问题讨论】:

    标签: swift firebase random


    【解决方案1】:

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

    }

    【讨论】:

      【解决方案2】:
      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)))]
      }
      

      【讨论】:

      • 谢谢,如果我有一百万条记录听起来会很沉重,是这样吗?
      • 我相信您会遇到一些延迟,如果您想减少应用程序端的负载,您可以尝试从 Google 的 Cloud Functions 执行此功能。
      • 知道为什么我的代码会出现以下错误。无法将“Int”类型的值转换为预期的参数类型“UInt32”。当我尝试将其转换为 UInt32 时,它会抛出 Cannot subscript a value of type '[DataSnapshot]' with a index of type 'UInt32'。
      • 试试return snapshots[arc4random_uniform(count - 1) as Int ]
      • 相同,然后它要求我像这样转换为 UInt32,返回快照 [arc4random_uniform(UInt32(count - 1)) 作为 Int ],然后抛出无法将类型 'UInt32' 的值转换为类型' Int'强制执行
      猜你喜欢
      • 1970-01-01
      • 2016-12-01
      • 2018-07-26
      • 1970-01-01
      • 1970-01-01
      • 2021-11-05
      • 2017-02-10
      • 1970-01-01
      • 2017-01-21
      相关资源
      最近更新 更多