I have the following UISearchbar code:
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSString* endpoint =[NSString stringWithFormat:@"http://www.someurl/",
[searchText stringByReplacingOccurrencesOfString:@" " withString:@"+"]];
NSURL* url = [NSURL URLWithString:endpoint];
NSURLRequest* request = [NSURLRequest requestWithURL:url];
GTMHTTPFetcher* myFetcher = [GTMHTTPFetcher fetcherWithRequest:request];
[myFetcher beginFetchWithDelegate:self didFinishSelector:@selector(searchResultsFetcher:finishedWithData:error:)];
}
I want to send this request after a pause in input and reset the timer everytime a character is hit. How can I do this?
Block text input to your search and have an NSTimer call a selector. Show an indicator of some sort so the user doesn't think something is going wrong. When the selector fires give control back to the user to continue typing
It doesn't have to use NSTimer.
Excellent code and working perfect for me. I found it here Replacing an NSTimer with performSelector:withObject:afterDelay. Thanks to Ben solution ... all bounties to him i just copy it here to be found easy
I was able to adapt Sven Tan's answer to my existing code in Swift. In my case, I am sending the string to a method that loads the search results async. Additionally, I am not using the UISearchBar but rather a plain old UITextField.
Here is the selector that is being called:
The way that
cancelPreviousPerformRequestsWithTarget
works is you need to pass the same target, selector, and object that was passed in theperformSelector
call in order for the previous request to be cancelled. In my implementation, since I am passing just a string, I need to preserve the current request string between calls so I can reference it to cancel requests.The result works for typing and deleting characters into my UITextField. Only one search is sent per major search term change.
Like I said, similar to what Sven Tan posted but slightly different usage. Hopefully this helps some people out.
In the
textDidChange
method create an NSTimer, say 2 seconds worth. If the timer already exists, invalidate and recreate the timer. (Untested code:)When the user stops typing for 2 seconds, -userPaused: will be called and your timer will be automatically invalidated (although not nil). When the user starts typing again a new timer will be setup.