I have a search display controller which hits an API endpoint. My current code will make a request to the API endpoint on every single char. What I want to do it make a request only when the user has stop typing for 500ms.
Here is the code:
In the UISearchDisplayDelegate
Note: searchQueue is an NSOperationQueue object.
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
[self.searchQueue cancelAllOperations];
[self.searchQueue addOperationWithBlock:^(){
[self.AFRequestManager.operationQueue cancelAllOperations];
NSString *access_token = [[FBSDKAccessToken currentAccessToken] tokenString];
NSDictionary *params = @{@"name": searchString, @"access_token": access_token };
NSString *getUrl = [baseUrl stringByAppendingString:@"api/users/search"];
[self.AFRequestManager GET:getUrl parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
self.searchedUsers = responseObject;
[self.searchDisplayController.searchResultsTableView reloadData];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
}];
return NO;
}
This delegate method gets called for every character that the user typed in and I would like to wait until the user finishes specifying the name.
I have tried using NSTimer
but it's messy. I can definitely pass the searchString to userInfo. However, once I invalidate the NSTimer, it cannot be used again.
I have tried using a dispatch_after
but actually that does not work because every time the user enter a char, the search is delayed but it is still making a request for every single character the user enters.
I did not want to overcomplicate but I feel like it should be super easy and I'm missing something.