Code Ratchet
Code Ratchet

Reputation: 6029

Handing an async call to Firestore

I have the following method inside my database.swift file:

func GetTestData(arg: Bool, completion: ([Tweet]) -> ()) {

        let db = Firestore.firestore()
        var tweets = [Tweet]()

        db.collection("tweets").getDocuments() {
            querySnapshot, error in

            if let error = error {
                print("unable to retrieve documents \(error.localizedDescription)")
            } else{
                print("Found documebts")
                tweets = querySnapshot!.documents.flatMap({Tweet(dictionary: $0.data())})
            }

        }

        completion(tweets)
    }

This method connects to Firestore retrieve data from a given collection, convert it into an array and then passes it back, I call this function with the following (located within my table view controller):

func BlahTest() {

        let database = Database()
        print("going to get documents")

        database.GetTestData(arg: true) { (tweets) in

            self.tweets = tweets

            self.tableView.reloadData()

        }


        print("after calling function")        
    }

The issue I have is when I run this my code is out of sync, and by that I mean print("after calling function") is called before print("Found documebts") which tells me it's not waiting for the async call to Firestore to finish, now I'm new to iOS development so would someone be willing to help me understand how I go about handling this?

Thanks in advance.

Upvotes: 1

Views: 1268

Answers (1)

Umair M
Umair M

Reputation: 10720

You are using closure block in your GetTestData() method. Anything that should be done after execution of this method must be done inside completion:

{
    (tweets) in
        self.tweets = tweets
        self.tableView.reloadData()

        // Do rest of stuff here.
}

Following are some resource about implementing async/await in swift like other languages:

1. Async semantics proposal for Swift

2. AwaitKit : The ES8 Async/Await control flow for Swift

3. Concurrency in Swift: One approach

4. Managing async code in Swift

Hope this helps :)

Upvotes: 5

Related Questions