6

I have a simple UITableView with UISearchBar/UISearchDisplayController that fetches results from remote ElasticSearch server by using RKObjectManager. Problem I have is that if user types to quickly or the term is a bit bigger several of requests fail and sometimes I don't get the results.

Is there an option to wait until user has stopped typing and then send request instead of sending request per each letter he types in?

vladexologija
  • 6,857
  • 4
  • 29
  • 28

2 Answers2

24

Add a small delay before sending the request, and then cancel that delayed request if the user continues typing

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    [NSObject cancelPreviousPerformRequestsWithTarget:self];

    [self performSelector:@selector(sendSearchRequest) withObject:searchText afterDelay:0.1f];
}

you may need to adjust the delay time. too long and its noticeable to the user that there is a delay, too short and you have the same problem as now

udjat
  • 479
  • 2
  • 10
wattson12
  • 11,176
  • 2
  • 32
  • 34
  • Any idea how to implement that in swift? – Ram Y May 14 '15 at 13:02
  • @Ram I've used the answers suggested here as a workaround for lack of performSelector in swift: http://stackoverflow.com/questions/24170282/swift-performselector-withobject-afterdelay – wattson12 May 15 '15 at 09:20
8

This is for swift version

NSObject.cancelPreviousPerformRequestsWithTarget(self)
self.performSelector("searchForText:", withObject: searchString, afterDelay: 0.5)
Avinash
  • 4,304
  • 1
  • 23
  • 18