0

I'm having trouble waiting for an asynchronous call and then populating the resulting addresses into placemarks for an MKMapView.

The issue is that only one placemark ends up showing on the map's view. I know the others exist because I've debugged it and seen such in the array. It's just not populating the map view fully/refreshing the MKAnnotation's assigned to it.

    // Load user sales
    myFirebaseController.loadSales(){(result: [SaleModel]) in
        // Assign result
        self.salesList = result

        let geocoder = CLGeocoder()

        let myGroup = DispatchGroup()

        // For each sale loaded in
        for sale in self.salesList{
            myGroup.enter()

            // Decode the address into coordinates
            geocoder.geocodeAddressString(sale.saleAddress!, completionHandler: {(placemarks, error) -> Void in
                if((error) != nil){
                    print("Error", error!)
                }

                if let placemark = placemarks?.first {
                    // Set the coordinate
                    let coordinates:CLLocationCoordinate2D = placemark.location!.coordinate

                    // Add the annotation
                    self.createMapAnnotation(coordinate: coordinates, title: sale.saleTitle!, address: sale.saleAddress!)
                }

                myGroup.leave()
            })
        }

        myGroup.notify(queue: .main){
            for annotation in self.mapView.annotations {
                self.mapView.removeAnnotation(annotation)

                self.mapView.addAnnotation(annotation)
            }
        }
    }

As you can see once the dispatch group is left, I try to remove all annotations and re-add them, as a means to refresh it, though I think this is a poor attempt and obviously it doesn't change the map view (which only records the first sale annotation of the self.salesList)

What am I doing wrong here?

Note:self.createMapAnnotation() adds an annotation to the map view.

EDIT: I tried following this - Wait until swift for loop with asynchronous network requests finishes executing but it doesn't seem to help my situation

ChewySalmon
  • 576
  • 5
  • 22

1 Answers1

0

Try writing below code after completion of the loop in myGroup.notify(queue: .main) method.

self.mapView?.showAnnotations((self.mapView?.annotations)!, animated: true)
Deepak Kumar
  • 175
  • 9
  • Hmm, doesn't seem to work. I think the issue is that `myGroup.notify(queue: .main)` is only called once and not for each geocode thread – ChewySalmon Jun 11 '17 at 08:04