简体   繁体   中英

How to enter a DispatchGroup in a firebase firestore callback

I have this function where I want to play an animation until the fetching of my data is complete. I have this variable "loadFetchDone" to indicate that. I need to use snapshotListener when I fetch my data from firebase.

    func getLoads(completion: @escaping () -> ()){
    
    bookedLoadsListener = db.collectionGroup("allLoads").whereField("cv", isEqualTo: 1).whereField("status", isEqualTo: "Booked").order(by: "DateBooked", descending: false).addSnapshotListener{ (snapshot, err) in
        
        if err != nil{print("Error getting docs in TruckTrackingView.swift: \(err)")}
        

        loadFetchDone = false
    
        loads = []
        let lGroup = DispatchGroup()
        
    
        
        for load in snapshot?.documents ?? []{

                lGroup.enter()
                
                        ...

                        lGroup.leave()
               
                   
                }
            }
        }
        lGroup.notify(queue: .main){
            completion()
        }
    }
}

I use this function to get the loads. Once it completes, I set loadFetchDone to true which then stops the loading animation.This is how I call the function

        .onAppear(){
        
            globalGroup.enter()
            getLoads {
                globalGroup.leave()
            }
        globalGroup.notify(queue: .main){
                loadFetchDone = true
            }
    
    }

If this was a normal getDocuments call, then there wouldn't be a problem but since I am using snapshotListeners, if a change in the document is made, The globalGroup is never entered. This then results in the EXC BAD INSTRUCTION since I leave the group without ever entering it. I have tried entering the group inside the snapshotListener but It never notifies the globalGroup.

Then simply move the dispatch logic out of the view's lifecycle and into the database return, which is how you should handle it anyway IMO. Do all of your entering and exiting within the Firestore return closure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM