TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Firebase .order(by:) & .whereField with .addSnapshotlistener??

Forums > SwiftUI

Hi, 

Is it possible to combine .order(by:) & .whereField on two different fields in a collection on Firebase and use the .addSnapshotlistener?? It works on load but when I add an item to the list it won’t update the list. When I restart the app then it updates the list…

I find very little to almost no information about this on the internet and I've been stuck with my app for 2 weeks because I can't find a solution for this...

Thank you in advance if anyone finds some time to look into this.

import FirebaseFirestoreSwift
import SwiftUI

struct WorkingTeacherModel: Codable {
    @DocumentID var id: String? // @DocumentID to fetch the identifier from Firestore
    var name: String
    var startTime: String
    var startDate: String
    var establishment: String
    var room: String
}
import FirebaseFirestore
import SwiftUI

class WorkingTeacherViewModel: ObservableObject {

    @Published var workingTeachers = [WorkingTeacherModel]() // Reference to Model
    private var db = Firestore.firestore()

    func searchWorkingTeacher(name: String, teachersArray: [WorkingTeacherModel]) -> Int? {
        return teachersArray.firstIndex { $0.name == name }
    }

    func addData(name: String, establishment: String, room: String) {
        let startTimeFormatter =  DateFormatter()
        let endTimeFormatter =  DateFormatter()
        var startTime: String {
            startTimeFormatter.timeStyle = .medium
            startTimeFormatter.locale = Locale(identifier: "nl_BE")
            return startTimeFormatter.string(from: Date.now)
        }
        var startDate: String {
            endTimeFormatter.dateStyle = .short
            endTimeFormatter.locale = Locale(identifier: "nl_BE")
            return endTimeFormatter.string(from: Date.now)
        }
        do {
            _ = db.collection("WorkingTeachers").addDocument(data: ["name": name, "startTime": startTime, "startDate": startDate, "establishment": establishment, "room": room])
        }
    }

    func fetchDataForWorkingTeacherView(establishment: String) {
        db.collection("WorkingTeachers")
            .whereField("establishment", isEqualTo: establishment)
            .order(by: "startTime", descending: true)
            .addSnapshotListener { (querySnapshot, error) in
                guard let documents = querySnapshot?.documents else {
                    print("No documents")
                    return
                }
                self.workingTeachers = documents.compactMap { queryDocumentSnapshot -> WorkingTeacherModel? in
                    return try? queryDocumentSnapshot.data(as: WorkingTeacherModel.self)
                }
            }
    }
}
import FirebaseFirestore
import SwiftUI

struct WorkingTeacherView: View {
    @ObservedObject private var savedEstablishmentViewModel = SavedEstablishmentViewModel()
    @ObservedObject private var workingTeacherViewModel = WorkingTeacherViewModel()
    @ObservedObject private var savedTeacherViewModel = SavedTeacherViewModel()

    var body: some View {
        VStack {
            Text("Vandaag aanwezig in\n\(savedEstablishmentViewModel.establishmentName)")
            NavigationStack {
                VStack {
                    HStack {
                        List {
                            ForEach(workingTeacherViewModel.workingTeachers, id: \.id) { workingTeacher in
                                //WorkingTeacherRowView(workingTeacher: workingTeacher)
                                HStack {
                                    Text(workingTeacher.name)
                                    Spacer()
                                    Text(workingTeacher.startTime)
                                }
                            }
                            .listStyle(.plain)
                        }
                    }
                }
            }
        }
        .onAppear() {
            workingTeacherViewModel.fetchDataForWorkingTeacherView(establishment: savedEstablishmentViewModel.establishmentName)
        }
    }

Best Regards, Brecht

3      

Ok, I needed to create a composite index but I didn't see the message (link) in the console to create the index. Now it works as expected 😊

3      

Hacking with Swift is sponsored by Blaze.

SPONSORED Still waiting on your CI build? Speed it up ~3x with Blaze - change one line, pay less, keep your existing GitHub workflows. First 25 HWS readers to use code HACKING at checkout get 50% off the first year. Try it now for free!

Reserve your spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.