iOS: Call function after a few seconds the user did finish typing

笑着哭i 提交于 2019-12-23 05:20:02

问题


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



来源:https://stackoverflow.com/questions/13277974/ios-call-function-after-a-few-seconds-the-user-did-finish-typing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!