Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get current city and country from CLGeocoder?

I've been all over the internet trying to find out how to get the city and country from CLGeocoder. I can get the longitude and latitude easily but I need the city and country information, and I keep running into deprecated methods and such, any ideas? It basically needs to get the location, then have an NSString for the country, and an NSString for the city, so I can use them to look up more info or put them on labels, etc.

like image 696
Jon Sullivan Avatar asked Jan 29 '13 05:01

Jon Sullivan


People also ask

How do you reverse geocoding in Swift?

Reverse Geocoding With Swift. Reverse geocoding is a simple concept. We hand the CLGeocoder class a set of coordinates, latitude and longitude, and ask it for the corresponding address, a physical location that has meaning to the user.

What is CLGeocoder?

An interface for converting between geographic coordinates and place names.

What is CLLocation in Swift?

A CLLocation object contains the geographical location and altitude of a device, along with values indicating the accuracy of those measurements and when they were collected. In iOS, a location object also contains course information — that is, the speed and heading in which the device was moving.


1 Answers

You need to revise your terminology a bit - CLGeocoder (and most geocoders) won't give you a 'city' per-se - it uses terms such as 'Administrative Area', 'Subadministrative Area', etc. The CLGeocoder object will return an array of CLPlacemark objects which you can then query for the information you need. You init a CLGeocoder and call the reverseGeocodeLocation function with a location and a completion block. Here's an example:

    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);

     }];
    }

Now note that the CLPlacemark doesn't have a 'city' property. The full list of properties can be found here: CLPlacemark Class Reference

like image 190
Jai Govindani Avatar answered Oct 12 '22 13:10

Jai Govindani