0

I am trying to append my annotationsToReturn array and everytime i do that and then check the array count, it always returns 0 as if it never got appended. Could someone help me out please?

func fetchLocations(usersID: [String]){
    
    var annotationsToReturn : [UserAnnotations] = []
    
    for user in usersID {
        COLLECTION_USER.document(user).getDocument { snapshot, err in
            if err != nil {
                print("ERROR")
                return
            }
            
            
            let data = snapshot?.data() as? [String:Any] ?? [:]
            
            
            let latitude = data["latitude"]
            let longitude = data["longitude"]
            
            print("latitude: \(latitude as! CLLocationDegrees)")
            
            annotationsToReturn.append(UserAnnotations(user: User(dictionary: data), coordinate: CLLocationCoordinate2D(latitude: latitude as! CLLocationDegrees, longitude: longitude as! CLLocationDegrees)))
            

            
            
        }

    }

    print("count: \(annotationsToReturn.count)")

}
burnsi
  • 6,194
  • 13
  • 17
  • 27
  • Without knowing too much about the rest of your code, could it be possible that your loop is simply not running? i.e. if `usersID` is empty? – Microbob Jul 22 '22 at 17:52
  • i already did tests for that, usersID is not empty – bruce_blake Jul 22 '22 at 17:56
  • 3
    The other thing that could be happening is that your firebase request `getDocument` is asynchronous and takes time to run. So your swift code will continue on and print the count before the loop is done working, giving you an array of 0. Try to see if you can put your count print after the firebase stuff is for sure done – Microbob Jul 22 '22 at 18:03
  • This is an asynchronous issue.. The `print` statement is executing way before the data is returned from Firebase and the `annotationsToReturn` array is populated. Please see [this](https://stackoverflow.com/questions/65002514/how-can-i-get-document-data-and-reference-data-at-same-time-firestore-swift/65042420#65042420) and perhaps [this](https://stackoverflow.com/questions/66162801/fetch-document-only-once-when-firestore-has-updated/66186682#66186682) and then [this](https://stackoverflow.com/questions/63062031/how-do-i-save-data-from-cloud-firestore-to-a-variable-in-swift) – Jay Jul 22 '22 at 19:20
  • Oh and [this](https://stackoverflow.com/questions/68047113/swiftui-wait-until-firestore-getdocuments-is-finished-before-moving-on) has a lot of great info! – Jay Jul 22 '22 at 19:21

0 Answers0