ttungmayy
ttungmayy

Reputation: 3

Get data from Firestore document and append to array

Here is the firestore, where there is a collection of ingredients consisting of ingID, and each ingID has 4 fields

image of my firestores

I have [String] of ingID like this : ["ing1", "ing2", ...] called byDeptIngredientID
I want to get departmentEN of each ingID so I have this code in viewController:

for id in byDeptIngredientID {
    print("start-function")
    GroceryAPI().getIngredientDept(ingID: id)
    print("finish-function")
}

Then I have this code in another file call GroceryAPI. This is how I get the departmentEN field:

func getIngredientDept(ingID: String) {
     var byDeptIngredientDept = [String]()
     let ingredientList = Firestore.firestore().collection("ingredients").document(ingID)

     ingredientList.getDocument { (document, err) in
        print("appending...")
        self.deptIngredient.append(document!.get("departmentEN") as! String)
     }
     print("deptIngredient => \(self.deptIngredient)")
}

As you can see that I append the departmentEN into deptIngredient, but when I print out it afterwards, the result is just empty [ ]. The result is as following:

start-function
deptIngredient => []
finish-function
appending...
appending...
appending...

So it just skip the getDocument to do other stuff then come back to do it last ? Kind of async problem maybe ? But I want deptIngredient to be like ["dept1", "dept2", ...] for further use.

Any idea how to fix this ? Thank you in advance.

PS. I have tried DispatchGroup with DispatchQueue, no luck on that.

Upvotes: 0

Views: 101

Answers (1)

GIJoeCodes
GIJoeCodes

Reputation: 1850

Please try the code below

let docRef = Firestore.firestore().collection("ingredients").document(ingID)

docRef.getDocument { (document, error) in
    if let document = document, document.exists {
       let data = document.data()
       let dataDescription = data.map(String.init(describing:)) ?? "nil"
       print("Document data: \(dataDescription)")

       let ingredient = data["departmentEN"] as? String ?? ""
       self.deptIngredient.append(ingredient)

    } else {
        print("Document does not exist")
    }
}

Upvotes: 1

Related Questions