iOS: Call function after a few seconds the user di

2019-06-14 05:00发布

问题:

I'd like to create an UISearchBar function, which gets called like the search in the App Store: Execute the function (NSURLConnection) after a few seconds (NSTimer) the user did finish typing and just one time for this period.

Does anyone have an idea?

EDIT

    self.currentTaskID = self.currentTaskID + 1;
    NSInteger taskID = self.currentTaskID;

    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC), queue, ^{
        if (taskID == self.currentTaskID)
        {
            NSMutableURLRequest *request_CH3 = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://website.com/search.php?term=%@", replaceWhiteSpace]]
                                                               cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                           timeoutInterval:30.0];

            [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];

            authConnection_CH3 = [[NSURLConnection alloc] initWithRequest:request_CH3 delegate:self];
        }
    });

回答1:

I recently made an answer for similar question, you can find it here

Basically you can queue your searches with delay and dismiss any previously scheduled search if new comes in within specified period.



回答2:

Instead of using timers to do this, implement the delegate function of the UISearchBar, searchBarTextDidEndEditing or searchBar:textDidChange and then when you are satisfied with the number of characters that the user entered you will start your NSURLConnection request



回答3:

In the function where you want to call the search function (in your case after clicking)

implement this :

[timer invalidate];
    timer = nil;
    timer = [NSTimer scheduledTimerWithTimeInterval: 3.0 target: self selector: @selector(thefunctionyouwanttocall) userInfo: nil repeats: NO];

this will call your function 3 seconds after the click event