How do I retrieve a random object from Firebase using a sequential ID?

给你一囗甜甜゛ 提交于 2019-11-28 14:34:51

QUERY RANDOM OBJECT IN FIREBASE < VERY SIMPLE SOLUTION > 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'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 
    }

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

}

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)))]
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!