从CLGeocoder获取当前的城市和国家?

Jon*_*van 10 nsstring ios currentlocation clgeocoder ios6

我一直在互联网上试图找到如何从这个城市和国家CLGeocoder.我可以轻松获得经度和纬度,但我需要城市和国家的信息,而且我一直在使用已弃用的方法等等,任何想法?它基本上需要获取位置,然后有一个NSString国家和一个NSString城市,所以我可以使用它们查找更多信息或将它们放在标签上等.

Jai*_*ani 18

您需要稍微修改一下术语 - CLGeocoder(以及大多数地理编码器)本身不会给您"城市" - 它使用诸如"管理区域","子管理区域"等术语.CLGeocoder对象将返回一组CLPlacemark对象,然后您可以查询所需的信息.您初始化CLGeocoder并使用位置和完成块调用reverseGeocodeLocation函数.这是一个例子:

    if (osVersion() >= 5.0){

    CLGeocoder *reverseGeocoder = [[CLGeocoder alloc] init];

    [reverseGeocoder reverseGeocodeLocation:self.currentLocation completionHandler:^(NSArray *placemarks, NSError *error)
     {
         DDLogVerbose(@"reverseGeocodeLocation:completionHandler: Completion Handler called!");
         if (error){
             DDLogError(@"Geocode failed with error: %@", error);
             return;
         }

         DDLogVerbose(@"Received placemarks: %@", placemarks);


         CLPlacemark *myPlacemark = [placemarks objectAtIndex:0];
         NSString *countryCode = myPlacemark.ISOcountryCode;
         NSString *countryName = myPlacemark.country;
         DDLogVerbose(@"My country code: %@ and countryName: %@", countryCode, countryName);

     }];
    }
Run Code Online (Sandbox Code Playgroud)

现在请注意,CLPlacemark没有"城市"属性.完整的属性列表可以在这里找到:CLPlacemark类参考

  • 很好的答案.为了澄清,您可以通过访问`CLPlacemark*myPlacemark`object的`addressDictionary`属性中的"City"键来获取城市名称:即`myPlacemark.addressDictionary [@"City"]`但这在阅读后应该很明显你提到的文档:) (6认同)