Search code examples
firebaselistviewgoogle-cloud-firestoreswiftui

question..how can i get my firebase array of items to display in my swiftui list in order by date/time?


My Firebase item "Date" is shown

[Screen to display list is out of order]

//Here is my fetch statement, and you can see i tried this "order(by: "Date"). didnt work.

    func fetchTechPapers(_ meet: Meeting){
    let uid = meet.uid
    FirestoreConstants.MeetingsCollection.document(uid).collection("Technical").order(by: "Date", descending: false).getDocuments{ documentsSnapshot, error in
        if let error = error {
            self.errorMessage = "Failded to fetch contacts: \(error)"
            print("Failded to fetch contact: \(error)")
            return
        }
        documentsSnapshot?.documents.forEach({ snapshot in
            let paper = try? snapshot.data(as: BreakOuts.self)
            self.papers.append(paper!)
        })
    }
}

//Here is the list for my view:

                List{
                ForEach(vm.papers) { paper in
                    ZStack{
                        NavigationLink(value: paper) {
                            EmptyView()
                        }.opacity(0.0)
                        
                        PapersRowView(paper: paper, viewModel: vm)
                    }
                }
                .onAppear(perform: {
                })
            }

Any ides or direction to where i could go to read how this is done id appreciate it.


Solution

  • The Date field in your database holds a string value, and (as shown in the documentation on data types) Firestore orders string values lexicographically. In that order, your "12/20/2023 6:00pm" value comes after "11/21/2024 8:05pm". Chronologically that's not correct, but since these are strings it's what ends up happening.

    There is no option to have the database chance it's sort order to accommodate your use-case. Your options are to:

    • Store the value as an actual Date or Timestamp value, which ensures that Firestore then orders them chronologically.
    • Store the value in a string format that allows sorting the way you'd want, such as "2023/12/20 18:00". For more such formats, see ISO-8601.