Tiago Scolari

bits for fun

Asynchronous UISearchBar / UISearchDisplayController With Autocomplete


This is my second week working with objective-c and iphone. The task is to make a search with autocomplete. Both search and autocomplete should get results from a remote webservice. I was searching google about how to populate a UISearchDisplayController with remote data, asynchronously of course, when I found a great guide here.

I already had a working datasource for autocomplete:

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
    [_autocompleteDataSource searchFor:searchString];
    return NO;

The trick was to reload the tableview data in my datasource ([tableView reloadData]), when it finishes loading.

The autocomplete should make a full search when a suggestion or the search button is clicked. Therefore we must link that to trigger the real search. These are the methods that need to be overwritten:

  • searchBarSearchButtonClicked - triggered when the button is clicked
  • tableView:didSelectRowAtIndexPath - triggered when an item is clicked
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
    [self searchFor:searchBar.text];
    [searchBar setShowsCancelButton:NO animated:YES];

- (void)tableView:(UITableView *)tableView
    didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    Program *program = [_autocompleteDataSource objectInListAtIndex:indexPath.row];
    [self searchFor: program.name];
    [self normalRowClick:indexPath];

- (void)searchFor:(NSString *)searchTerm
    [_programs removeAllObjects];
    [_programs loadSearch:searchTerm];
    self.tableView.dataSource = _programs;
    [self.tableView reloadData];
    [self.searchDisplayController setActive:NO];
    [self.searchBar resignFirstResponder];

This triggers the final search. The self.tableview in the code is the view’s tableview, which is populated with the _programs datasource.

** Edit ** Final/working version of the search/app