5

I receive MKLocalSearchCompletion items from MKLocalSearchCompleter to its delegate. Every MKLocalSearchCompletion contains a title and a subtitle, the subtitle is an address. I need to extract a city and a country from the address. Please help!

Dmytro Skorokhod
  • 424
  • 8
  • 17

2 Answers2

10

Please use the following code:

MKLocalSearchRequest *request = [[MKLocalSearchRequest alloc] init];
request.naturalLanguageQuery = @"1 Infinite Loop Cupertino, CA 95014"; 
request.region = _mapView.region;
MKLocalSearch *search = [[MKLocalSearch alloc] initWithRequest:request];
[search startWithCompletionHandler:^(MKLocalSearchResponse *response, NSError *error) {
    //NSLog(@"Map Items: %@", response.mapItems);
    if (response.mapItems.count>0) {
        for (MKMapItem *item in response.mapItems) {
            //NSLog(@"Place: %@",[item valueForKey:@"place"]);
            NSDictionary *dictStructuredAddress = [[[item valueForKey:@"place"] valueForKey:@"address"] valueForKey:@"structuredAddress"];
            NSLog(@"Structured Address : %@",dictStructuredAddress); 
            NSLog(@"Country & City : %@ & %@",[dictStructuredAddress valueForKey@"country"],[dictStructuredAddress valueForKey@"locality"]);
        }
}];

Inside this dictStructuredAddress you can get country, city, etc.

Arasuvel
  • 2,971
  • 1
  • 25
  • 40
Poles
  • 3,585
  • 9
  • 43
  • 91
  • It doesn't have such values! – Michał Ziobro Mar 22 '19 at 14:46
  • some : 1 element - 0 : { isCurrentLocation = 0; name = Chile; placemark = "Chile, Chile @ <-34.57297600,-71.09573240> +/- 0.00m, region CLCircularRegion (identifier:'<-39.31833481,-87.92901825> radius 2628724.37', center:<-39.31833481,-87.92901825>, radius:2628724.37m)"; timeZone = "America/Santiago (GMT-3) offset -10800 (Daylight)"; } – Michał Ziobro Mar 22 '19 at 14:47
  • This is awesome, but I am having trouble converting it to Swift, specifically the dictStructuredAddress with the chained valueForKey. – erickva May 02 '19 at 09:21
  • @erickva: print only `item["place"]` then you will get the actual keys. – Poles May 07 '19 at 13:20
  • @Poles what I found impossible was to parse the keys returned from item["place"], weirdly. – erickva May 17 '19 at 06:06
4

MKLocalSearchCompletion does not "contain an address". It contains a title and subtitle. To get more information, use the MKLocalSearchCompletion to form an MKLocalSearchRequest and perform the MKLocalSearch.

matt
  • 515,959
  • 87
  • 875
  • 1,141