IOS - web service request after delay

I have a search bar with UITableView suggestions that are populated (using JSON services) as user types. These service calls should be made after a delay of 500 ms without input. If the user starts to enter this period of 500 ms, the current call in the queue must be canceled, and the application must wait another 500 ms of inactivity before making another afterDelay call. I know that I have to use performSelector:withObject:afterDelay in all this situation, but I cannot do with the proper conditions. I tried using a bunch of bools, but it just got dirty ... Any help?

+4
source share
2 answers

I would use NSTimer instead of performSelector:withObject:afterDelay: Detect when text changes to UISearchBar and reset to timer.

 -(void)viewDidLoad { search.delegate = self; } -(void)searchBar:(UISearchBar *)theSearchBar textDidChange:(NSString *)searchText { [timer invalidate]; timer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(callTheService) userInfo:nil repeats:NO]; } 
+7
source

How about this if you detect text input in the UITextFieldDelegate method:

 - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(sendNetworkRequest) object:nil]; [self performSelector:@selector(sendNetworkRequest) withObject:nil afterDelay:0.5]; return YES; } - (void)sendNetworkRequest { // Here immediately send the request } 

I like this rating for such problems, as it means I don’t need to use NSTimer or track any state, whether I expect to see more text entered or not. Hope this helps! Let me know if you have any questions.

EDIT:. You see that you are using the search bar instead. The principle is the same, just put the pairing / pairing in the corresponding UISearchBarDelegate method.

+6
source

Source: https://habr.com/ru/post/1432338/


All Articles