I need to call the calculate() method of the MKDirections class in a for loop but I am making too many requests for a valid distance to be returned. I have tried putting in a while loop that keeps looping until the isCalculating property is set to false but I am still making too many requests as evidenced by the error.debugDescription message that prints out. How can I wait for the current request to finish before submitting another one?

I have tried putting in a while loop to delay submitting another request to the calculate() method but the code just keeps making too many requests as evidenced by the error.debugDescription.

// Step through sites one by one
for siteIndex in 0..<countySites.count {
    var selectedSite = countySites[siteIndex]
    let destinationPlacemark = MKPlacemark(coordinate: selectedSite.locationCoordinate)

    request.destination = MKMapItem(placemark: destinationPlacemark)

    let distanceAndDirections = MKDirections(request: request)
    if currentCoordinate != nil {

        busyCalculating = distanceAndDirections.isCalculating
        while busyCalculating == true {
            busyCalculating = distanceAndDirections.isCalculating

        distanceAndDirections.calculate { (response, error) in

            if error == nil {

                let distanceInMetres = response?.routes.first?.distance
                let distanceInMiles = distanceInMetres! / 1610
                let roundedDistanceInMiles = Int(distanceInMiles.rounded())
                let distanceToSite = roundedDistanceInMiles

                selectedSite.distance = distanceToSite
                self.countySites[siteIndex] = selectedSite

            } else {
                print("error is not nil = \(error.debugDescription)")




Related posts

Recent Viewed