0

I am storing data in my firebase database but when I want to retrieve the differents name of my users, unlike my profile image who is retrieving from most recent, the names are retrieving in alphabetical orders... here's my code :

 func getNamesUser(){
    let rootRef = Database.database().reference()
    let query = rootRef.child("users").queryOrdered(byChild: "name")
    query.observeSingleEvent(of: .value) { (snapshot) in
        let nameArray = snapshot.children.allObjects as! [DataSnapshot]
        for child in nameArray{
            let value = child.value as? NSDictionary
            let child = value?["name"] as? String
            self.arrayName.append(child!)
        }
        self.collectionView.reloadData()
    }
}

func getImgUser(){
    let rootRef = Database.database().reference()
    let query = rootRef.child("users").queryOrdered(byChild: "profileImgURL")
    query.observeSingleEvent(of: .value) { (snapshot) in
        let nameArray = snapshot.children.allObjects as! [DataSnapshot]
        for child in nameArray{
            let value = child.value as? NSDictionary
            let child = value?["profileImgURL"] as? String
            self.arrayProfilImage.append(child!)
        }
        self.collectionView.reloadData()
    }
}

and here's my firebase database tree :

enter image description here

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Bou Bou
  • 33
  • 7
  • What is your question? – koen Mar 02 '20 at 18:54
  • how do I get the names from most recent instead of alphabetical order – Bou Bou Mar 02 '20 at 19:05
  • 1
    Do the users have a timestamp so you can check which ones are the most recent? – koen Mar 02 '20 at 19:07
  • no I need to add one ? – Bou Bou Mar 02 '20 at 19:13
  • I am not familiar with Firebase, but if you want to search by date, that seems to be the way to go. – koen Mar 02 '20 at 19:14
  • hum all right ill try to search how to do this with timestamp thanks, still if anyone have another idea... – Bou Bou Mar 02 '20 at 19:16
  • See for instance: https://stackoverflow.com/questions/41765126/query-latest-entries-using-firebase-in-swift – koen Mar 02 '20 at 19:28
  • Koen has it right here: as far as I can see nothing in your JSON indicates recency. Firebase doesn't automatically add any such info, so you will add a timestamp yourself. If correctness matters, you'll want to [use a server-side timestamp](https://firebase.google.com/docs/database/ios/offline-capabilities#server-timestamps) for that, so that users can't add an inaccurate value. – Frank van Puffelen Mar 02 '20 at 19:52
  • yes I already added server side timestamp but idk how to fetch them sorted in my collection view – Bou Bou Mar 02 '20 at 20:16
  • You can sort your model array before calling `reloadData()`. See an example in the link I gave above. – koen Mar 02 '20 at 20:28
  • Also, it seems more practical to maintain only one array, instead of the two (or more) you have now. – koen Mar 02 '20 at 20:29

0 Answers0