Location Search Results overlay

ios, location, search

Solution

There is a standard component for doing that, called UISearchDisplayController.

It gives you a `UISearchBar` and a `UITableView` for displaying the results. Then you can customize the content and the appearance of the table view according to your needs.

In order to get control over the actions performed by such controller you will need to conform to the UISearchDisplayDelegate protocol.

I suggest you to look carefully at the example app you can find on the doc.

EDIT

In order to implement the autocompletion features you can implement the `searchDisplayController:shouldReloadTableForSearchString` method of the `UISearchDisplayDelegate` protocol. It will be called at every character typed by the user.

Assuming that you have a `CLGeocoder` property called `geocoder` and that you are holding the placemarks into an `NSArray` property called `placemarks`, here's an example of how you can achieve a live autocompletion:

-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {      
    [self.geocoder geocodeAddressString:searchString completionHandler:^(NSArray *placemarks, NSError *error) {
            self.placemarks = placemarks;
            [self.searchDisplayController.searchResultsTableView reloadData];
    }];
    return NO;
}

Everytime the input string for the search change, you perform a forward geocoding using such string. In the `completionHandler` block you assign the newly found placemarks to your `placemarks` property and reload the table.

Please not that since the search is asynchronous you will take care of reloading the table in the completion handler and return NO in the delegate method. Returning YES will make the table to reload before the search is over, which is not the behaviour you want.

As a final remark, remember that the code I provided is minimal. In a real-world app you'd better take care of the errors the geocoder may run into, such as `kCLErrorGeocodeFoundNoResult`, `kCLErrorGeocodeFoundPartialResult` and `kCLErrorGeocodeCanceled`, documented here.

Problem

I'm trying to add a Search Bar to one of my apps that lets a user enter address information, and a tableview appears with the possible results (and a keyboard). Essentially the same functionality provided in the Maps app. Is there an easy way to do this? It would be nice to have a Current Location default & autocomplete as well, but not necessary. I can build the UI from scratch, but I don't know how to get back the search results. Can I use geocoder and parse the results into a tableview?

Original source