2014-04-15 49 views
1

我有一個座標數組,我用for循環遍歷。我想在地圖上爲每個位置放置註釋,並將標註的字幕作爲座標的地址,使用reverseGeocodeLocation找到在for循環中,我調用reverseGeocodeLocation方法,並在完成塊內創建註釋並將其顯示在地圖上。但是,當我運行該應用程序時,只顯示一個註釋。我去了調試器,完成塊只被調用一次(對於兩個調用reverseGeocodeLocation方法)。任何建議來解決這個問題?reverseGeocodeLocation只執行完成塊一次

我的for循環:

for(int i = 0; i < [locations count]; i++) 
{ 
    CLLocation *location = [locations objectAtIndex:i]; 
    __block NSString *info; 
    NSLog(@"Resolving the Address"); 
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) 
    { 
     NSLog(@"Found placemarks: %@, error: %@", placemarks, error); 
     if (error == nil && [placemarks count] > 0) 
     { 
      placemark = [placemarks lastObject]; 
      info = [NSString stringWithFormat:@"%@ %@ %@ %@, %@", 
        placemark.subThoroughfare, placemark.thoroughfare, 
        placemark.postalCode, placemark.locality, 
        placemark.administrativeArea]; 
      [self remainderOfMethod:location withAddress:info atIndex:i]; 
     } 
     else 
     { 
      NSLog(@"%@", error.debugDescription); 
     } 
    } ]; 
} 

並號召在完成塊的方法:

- (void) remainderOfMethod: (CLLocation *)location withAddress:(NSString *)info atIndex: (int)i 
{ 
    MKPointAnnotation* annotation = [[MKPointAnnotation alloc] init]; 
    if (location != nil) 
    { 
     [annotation setSubtitle:[NSString stringWithFormat:@"%@", info]]; 
     annotation.coordinate = location.coordinate; 
     [self.mapView addAnnotation:annotation]; 
    } 
} 

謝謝!

+0

爲什麼'info'聲明在'completionHandler'塊之外?似乎沒有必要 –

+0

無論哪種方式,猜測只是不好的編碼風格。 –

回答

3

從蘋果官方文檔:

啓動反向地址解析請求後,不要試圖 啓動另一個反向或正向地址解析請求

你可以在這裏找到文檔:https://developer.apple.com/library/ios/documentation/CoreLocation/Reference/CLGeocoder_class/Reference/Reference.html#//apple_ref/occ/instm/CLGeocoder/reverseGeocodeLocation:completionHandler

解決此問題的一種方法是在遞歸方法中一次只執行一個請求,該方法在每次迭代中從堆棧(或數組)中彈出一個位置。

即使在這種情況下,考慮一下蘋果不得不說的是:

的地址解析請求的速率限制爲每個應用程序,在很短的時間內使拍過多 要求可能導致一些 失敗的請求

因此,您可能需要按需請求地理編碼,例如,當用戶點擊註釋時。

+0

當用戶點擊註釋是一個好主意!謝謝!但是,我允許用戶在表格視圖中查看所有位置,在這種情況下,我需要一次加載數據。任何想法? –

+0

在這種情況下,您可以使用遞歸方法。區別在於,在for循環中,會有多個地理位置併發請求。如果您在completionHandler完成後通過調用方法遞歸執行此操作,那麼您將確保只有一個活動的地理編碼請求。無論如何,這並不能解決蘋果爲每個應用程序提供的限制。我真的不知道限制是什麼。 –

+0

謝謝!我會檢查文件的限制 –