Search code examples
iphoneios5clgeocoder

geocode method not executing second time in the for loop


I have written following code to find out the coordinates of list of countries.

  int count=[objCountries.countryName count];
CLGeocoder *geoCode = [[CLGeocoder alloc] init];
for(int i=0;i<count;i++)
{
    NSString *strCountry=[[NSString alloc]initWithString:[objCountries.countryName objectAtIndex:i]];




        [geoCode geocodeAddressString:strCountry completionHandler:^(NSArray *placemarks, NSError *error)
    {
        if (!error)
        {
            CLPlacemark *place = [placemarks objectAtIndex:0];
            CLLocation *location = place.location;
            CLLocationCoordinate2D coord = location.coordinate;

            NSString *tempLati=[[NSString alloc]initWithFormat:@"%g",coord.latitude];
            NSString *tempLongi=[[NSString alloc]initWithFormat:@"%g",coord.longitude];
            NSLog(@"-------------------------");
            NSLog(@"Country : %@",strCountry);
            NSLog(@" Latitude : %@ ",tempLati);
            NSLog(@" Longitude : %@ ",tempLongi);

            [objCountries.countryLatitude addObject:tempLati];
            [objCountries.countryLongitude addObject:tempLongi];
            [db insertAsiaCountry:strCountry :tempLati :tempLongi];
        }
    }];

}

}

In my countryName array there 20 objects available

Problem: It's working Fine first time only. But Second Time when for loop executing [geocode geo....] method is not calling. I Can't understand what to do ? Please Help. Thank You Sir.


Solution

  • after this line..

        [db insertAsiaCountry:strCountry :tempLati :tempLongi];
    

    add

    [geoCode cancelGeocode];
    

    even if error occurs try allocating geoCoder wihtin the 'for' loop