iOS: Wait until user finishes typing and then send

2019-02-04 00:33发布

问题:

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?

回答1:

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



回答2:

This is for swift version

NSObject.cancelPreviousPerformRequestsWithTarget(self)
self.performSelector("searchForText:", withObject: searchString, afterDelay: 0.5)