Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS: Wait until user finishes typing and then send request

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?

like image 219
vladexologija Avatar asked Jul 01 '14 16:07

vladexologija


2 Answers

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

like image 173
wattson12 Avatar answered Oct 15 '22 11:10

wattson12


This is for swift version

NSObject.cancelPreviousPerformRequestsWithTarget(self)
self.performSelector("searchForText:", withObject: searchString, afterDelay: 0.5)
like image 32
Avinash Avatar answered Oct 15 '22 11:10

Avinash