M1X
M1X

Reputation: 5374

Swift Get CLPlacemark from CLLocation

I have an array of custom Item type. This model has a location and destination property of type CLLocation

After I fetch this item I want to make two requests using Geocoder to fetch the CLPlacemark for the destination and location. However it is strange that I can either make a call for the location or for the destination. If I do both the requests, only the first one fires. The seconds doesn't fire. As you can see after the first call I'm not replacing the whole model in the array but just altering a property so I do not think that's the problem.

for (i, element) in self.categories[index].items.enumerated() {
    // either this 
    self.geocoder.reverseGeocodeLocation(element.location, completionHandler: { (placemarks, error) in
        if let error = error {
            self.error = error.localizedDescription
        } else {
            self.categories[index].items[i].locationPlacemark = placemarks?.first
        }
    })

    // or this 
    self.geocoder.reverseGeocodeLocation(element.destination, completionHandler: { (placemarks, error) in
        if let error = error {
            self.error = error.localizedDescription
        } else {
            self.categories[index].items[i].destinationPlacemark = placemarks?.first
        }
    })
}

Upvotes: 1

Views: 482

Answers (1)

Paulw11
Paulw11

Reputation: 115051

You can't submit parallel reverse geocoding requests -

From the documentation

After initiating a reverse-geocoding request, do not attempt to initiate another reverse- or forward-geocoding request. Geocoding requests are rate-limited for each app, so making too many requests in a short period of time may cause some of the requests to fail. When the maximum rate is exceeded, the geocoder passes an error object with the value CLError.Code.network to your completion handler.

For a single Item you could save the problem by initiating the second geocoding request in the completion handler of the first, but this won't work for multiple items since you will submit several "first" requests in parallel.

You will need to adopt a more sophisticated approach, such as submitting operations to a serial operation queue.

Upvotes: 1

Related Questions