Home > Mobile >  How to call data from firebase synchronously
How to call data from firebase synchronously

Time:08-20

I have a function that calls data from my Firebase Database, but it is an async function, and messing up the other functions of my app. I have looked all around tutorials but they only show asyncronus functions, and my app depends on the Firebase Data to load first.

Code for the function:

@State var realLat: [String] = [ ]
@State var realLong: [String] = [ ]

func downloadFirebaseData() async throws -> Float {
        
        let group = DispatchGroup()
        group.enter()                // << start
        
        let db = Firestore.firestore()
        try withUnsafeThrowingContinuation { continuation in
            db.collection("annotations")
                .getDocuments { (querySnapshot, error) in
                    defer {
                        group.leave()    // << end on any return
                    }
                    
                    // result heading code here
                    if let Lat = i.document.get("lat") as? String {
                        DispatchQueue.main.async {
                            realLat.append(Lat)
                            print("downloadLatServerData() \(realLat)")
                        }
                    }
                }
        }
        group.wait()   // << block till leave
    }

The function DownloadFirebaseMapServerData() is an async function becuase of the line db.collection("annotations").addSnapshotListener {(snap, err) in... and I need realLat and realLong to be downloaded first inorder to assign them to a mapAnnotation, so is there any way that I could make this function syncronus or make another function with the same end goal? Also another thing to note is that realLat and realLong are both String Arrays, or Arrays that are Strings

CodePudding user response:

Ok, let's say that - try to avoid making synchronous API that designed asynchronous - it was done by purpose, long time-consuming bla-bla-bla

but, if it is needed technically it is possible, for example using dispatch groups, like

func downloadFirebaseData() async throws -> Float {
        
        let group = DispatchGroup()
        group.enter()                // << start

        let db = Firestore.firestore()
        try withUnsafeThrowingContinuation { continuation in
            db.collection("annotations")
                .getDocuments { (querySnapshot, error) in

                    defer {
                       group.leave()    // << end on any return
                    }

                    // result heading code here
                }
        }
        group.wait()   // << block till leave
}
  • Related