Google cloud firestore 如何在SwiftUI中的firebase查询期间显示加载动画

Google cloud firestore 如何在SwiftUI中的firebase查询期间显示加载动画,google-cloud-firestore,swiftui,Google Cloud Firestore,Swiftui,我正在用SwiftUI构建一个应用程序,并且有一个ObserveObject用于查询我的Firestore数据库。我的文档相对较大,经常需要查询很多文档,所以我想在查询下载数据时加入一些加载指示器 这是我创建的ObserveObject的一个示例: import FirebaseFirestore import SwiftUI struct Document: Identifiable, Equatable { var id: String var content: Strin

我正在用SwiftUI构建一个应用程序,并且有一个ObserveObject用于查询我的Firestore数据库。我的文档相对较大,经常需要查询很多文档,所以我想在查询下载数据时加入一些加载指示器

这是我创建的ObserveObject的一个示例:

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) }
}
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!])
    }
}
请记住,对于这个示例,数据几乎没有需要加载视图那么大,这几乎是即时的,但是对于我的应用程序,这段代码被分成不同文件和场景的加载,所以我想我应该创建这个示例

我尝试添加一个绑定布尔值,并在readData函数加载时切换它,但是SwiftUI得到了映射,我得到了一个错误

'在视图更新期间修改状态,这将导致未定义的行为。'

您需要在@observeObject中使用@Published,而不是@Binding

下面是一个可能的演示:

class Fetch: ObservableObject {
    @Published var loading = false

    func longTask() {
        self.loading = true
        // simulates a long asynchronous task (eg. fetching data)
        DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
            self.loading = false
        }
    }
}
您需要在@observeObject中使用@Published,而不是@Binding

下面是一个可能的演示:

class Fetch: ObservableObject {
    @Published var loading = false

    func longTask() {
        self.loading = true
        // simulates a long asynchronous task (eg. fetching data)
        DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
            self.loading = false
        }
    }
}

你好,我在使用这个代码snipet atm,有点小麻烦你介意看一下我的问题吗如果你有时间你好,我在使用这个代码snipet atm,有点小麻烦如果你有时间,你介意看一下我的问题吗
struct LoadingView: View {
    var body: some View {
        ZStack {
            Color.black
                .opacity(0.5)
                .edgesIgnoringSafeArea(.all)
            Text("Loading")
        }
    }
}