2013-07-13 25 views
0

這裏有一段示例代碼:如何從CLPlacemark獲取zipCode,我知道它始終爲空?

[_geoCoder reverseGeocodeLocation:self.locationManager.location // You can pass aLocation here instead 
       completionHandler:^(NSArray *placemarks, NSError *error) { 

        dispatch_async(dispatch_get_main_queue(),^ { 
         // do stuff with placemarks on the main thread 

         if (placemarks.count == 1) { 

          CLPlacemark *place = [placemarks objectAtIndex:0]; 
          // NSLog([place postalCode]); 
          NSString* addressString1 = [place thoroughfare]; 
          addressString1 = [addressString1 stringByAppendingString:[NSString stringWithFormat:@"%@",[place.addressDictionary objectForKey:(NSString*)kABPersonAddressZIPKey]]];// 
          NSLog(@"%@",addressString1);// is null ?? 
          NSlog(@"%@",place.postalCode);//is null ?? 

          //[self performSelectorInBackground:@selector(log) withObject:nil]; 
         } 

        }); 
       }]; 

回答

0

我猜你可能只有一個「壞」的座標,如果沒有郵政編碼存在。嘗試以下代碼片段。它應顯示各種信息和末端的郵政編碼'80802':

CLLocationCoordinate2D myCoordinates = { 48.167222, 11.586111 }; 
CLLocation *location = [[CLLocation alloc]initWithLatitude:myCoordinates.latitude longitude:myCoordinates.longitude]; 

CLGeocoder *geocoder = [[CLGeocoder alloc] init]; 
[geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) { 
    NSLog(@"%d Placemarks %@", placemarks.count, placemarks); 
    CLPlacemark *place = [placemarks objectAtIndex:0]; 
    NSLog(@"Placemark %@", place); 
    NSLog(@"Address Dictionary: %@", place.addressDictionary); 
    NSLog(@"Zip key %@", [place.addressDictionary objectForKey:(NSString *)kABPersonAddressZIPKey]); 

}]; 

在第一行插入不同的座標並試驗自己。

+0

@Klass,這段代碼不適用於許多經緯度。它只適用於你通過。有沒有其他方法? – Heena

+0

@Roshni,它在很大程度上取決於蘋果對不同國家的數據。在美國和德國,數據似乎相當不錯。另一種方法是使用Google Maps API及其反向地理編碼器:https://developers.google.com/maps/documentation/ios/reference/interface_g_m_s_geocoder – Klaas