0

I have an Array where some different UserID's are stored. Each UserID is connected with their corresponding data in Firestore. So now I want to fetch all the JSON Data from the UserID's and make them accessible to decode them later. Therefore the fetched Data (coming as a Dictionary) from each user must be accessible separately. I tried it with that way:

var fetchedIDs = ["ID1", "ID2", "ID3"]
var finalArray = [[String: Any]]()

for id in fetchedIDs{  
                let docRef = Firestore.firestore().collection("Data").document(id)
                docRef.getDocument { (document, error) in
                    if let document = document, document.exists {
                       let myDict: [String: Any] = document.data() as! [String: Any] 
                        finalArray.append(myDict)
                    }    
                }     
            }   
        }

But the problem is that the finalArray (like finalArray[0]) is just accessible in the For-Loop. It should be accessible outside of the loop and look like that:
finalArray[0] should have the Dictionary data from ID1
finalArray[1] should have the Dictionary data from ID2
Maybe I am thinking to complicated for that.. Can someone help me out ?

Is there generally a good source for learning about scopes and how the data should be accessed like in that scenario? Thanks!

  • Are you sure this isn’t an asynchronous issue and that you try to access it before the data has been downloaded? – Joakim Danielson Feb 23 '20 at 12:06
  • "Swift + Closure + Async" should be a good way to search. Do a print in `finalArray.append(myDict)` , do a print after the for loop. Which one will be printed first? – Larme Feb 23 '20 at 12:30
  • @Larme The print after the for loop is the first one printed. – LoopingLouieX Feb 23 '20 at 13:01
  • I know. It’s to point out the asynchrone of your code. Look as I said for « Swift async closure » – Larme Feb 23 '20 at 13:03

1 Answers1

1

Finally get it working with the following code:

var fetchedIDs = ["ID1", "ID2", "ID3"]
func loadData(com:@escaping( ([[String: Any]]) -> ())){
                var myArray = [[String: Any]]()

                for id in fetchedIDs{
                    let refLike = db.collection("Data").document(id)
                    refLike.getDocument { (document, error) in
                        if let err = error {
                            print("Error getting documents: \(err)")
                        } else {
                            let myDict: [String: Any] = document?.data() as! [String: Any]
                            myArray.append(myDict)
                        }
                        com(myArray)
                    }
                }
            }


            loadData(){ arr in
                if (arr.count == fetchedIDs.count){
                    print ("User 1 has the following data: \(arr[0])")
                    print ("User 2 has the following data: \(arr[1])")
                }
            }