I am building an app with SwiftUI, and have an ObservableObject for querying my Firestore database. My documents are relatively large and I often need to query a lot of them, so I wanted to incorporate some sort of loading indicator while the query is downloading the data.
This is an example of the ObservableObject I have created:
import FirebaseFirestore
import SwiftUI
struct Document: Identifiable, Equatable {
var id: String
var content: String
}
class Fetch: ObservableObject {
init(loading: Binding<Bool>) {
self._loading = loading
readDocuments()
}
@Published var documents: [Document] = []
@Binding var loading: Bool
var collection: CollectionReference = Firestore.firestore().collection("DOCUMENTS")
func newDocument(content: String) {
let id = self.collection.document().documentID
self.collection.document(id).setData(["id": id, "content": content]) { (error) in handleError(error: error, message: "\(id) CREATED") }
}
func deleteDocument(document: Document) {
if self.documents.contains(document) {
self.collection.document(document.id).delete() { (error) in handleError(error: error, message: "\(document.id) DELETED") }
} else { print("\(document.id) NOT FOUND") }
}
func updateDocument(document: Document, update: [String : Any]) {
if self.documents.contains(document) {
self.collection.document(document.id).updateData(update) { (error) in handleError(error: error, message: "\(document.id) UPDATED") }
} else { print("\(document.id) NOT FOUND") }
}
func readDocuments() {
self.collection.addSnapshotListener { (snapshot, error) in
handleError(error: error, message: "READ DOCUMENTS")
snapshot?.documentChanges.forEach({ (change) in
if change.type == .added {
self.loading = true
self.documents.append(Document(id: change.document.get("id") as? String ?? "FAILED TO READ",
content: change.document.get("content") as? String ?? "FAILED TO READ"))
self.loading = false
}
if change.type == .modified {
self.loading = true
self.documents = self.documents.map { (document) -> Document in
if document.id == change.document.documentID {
let modifiedDocument = Document(id: change.document.get("id") as? String ?? "FAILED TO READ",
content: change.document.get("content") as? String ?? "FAILED TO READ")
return modifiedDocument
} else {
return document
}
}
self.loading = false
}
if change.type == .removed {
self.loading = true
self.documents.removeAll(where: { $0.id == change.document.documentID })
self.loading = false
}
})
}
}
}
func handleError(error: Error?, message: String) {
if error != nil { print((error?.localizedDescription)!); return } else { print(message) }
}
This is the example view I have created:
struct ContentView: View {
@State var loading: Bool = false
var body: some View {
NavigationView {
if loading {
Color.blue.overlay(Text("Loading View"))
} else {
Subview(fetch: Fetch(loading: self.$loading))
}
}
}
}
struct Subview: View {
@ObservedObject var fetch: Fetch
@State var newDocumentContent: String = ""
var body: some View {
VStack(spacing: 0.0) {
List {
ForEach(self.fetch.documents) { document in
NavigationLink(destination:
UpdateDocument(fetch: self.fetch, documentID: document.id)) {
Text(document.content)
}
}.onDelete { indexSet in
self.deleteDocument(indexSet: indexSet)
}
}
Divider()
NewDocument(fetch: self.fetch, newDocumentContent: self.$newDocumentContent)
}.navigationBarTitle("CRUD", displayMode: .inline)
}
func deleteDocument(indexSet: IndexSet) {
self.fetch.deleteDocument(document: self.fetch.documents[indexSet.first!])
}
}
Keep in mind for this example the data is not nearly as big to need a loading view, this is pretty much instant, but for my application this code is split into loads of different files and scenarios so I thought I'd create this example.
I have tried adding a binding boolean and toggling it when the readData() function is loading, but SwiftUI gets map and I get an error.
'Modifying state during view update, this will cause undefined behavior.'