How to throttle search (based on typing speed) in iOS UISearchBar? How to throttle search (based on typing speed) in iOS UISearchBar? ios ios

How to throttle search (based on typing speed) in iOS UISearchBar?


Try this magic:

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{    // to limit network activity, reload half a second after last key press.    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(reload) object:nil];    [self performSelector:@selector(reload) withObject:nil afterDelay:0.5];}

Swift version:

 func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {    // to limit network activity, reload half a second after last key press.      NSObject.cancelPreviousPerformRequestsWithTarget(self, selector: "reload", object: nil)      self.performSelector("reload", withObject: nil, afterDelay: 0.5) }

Note this example calls a method called reload but you can make it call whatever method you like!


For people who need this in Swift 4 onwards:

Keep it simple with a DispatchWorkItem like here.


or use the old Obj-C way:

func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {    // to limit network activity, reload half a second after last key press.    NSObject.cancelPreviousPerformRequestsWithTarget(self, selector: "reload", object: nil)    self.performSelector("reload", withObject: nil, afterDelay: 0.5)}

EDIT: SWIFT 3 Version

func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {    // to limit network activity, reload half a second after last key press.    NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(self.reload), object: nil)    self.perform(#selector(self.reload), with: nil, afterDelay: 0.5)}func reload() {    print("Doing things")}


Improved Swift 4:

Assuming that you are already conforming to UISearchBarDelegate, this is an improved Swift 4 version of VivienG's answer:

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {    NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(self.reload(_:)), object: searchBar)    perform(#selector(self.reload(_:)), with: searchBar, afterDelay: 0.75)}@objc func reload(_ searchBar: UISearchBar) {    guard let query = searchBar.text, query.trimmingCharacters(in: .whitespaces) != "" else {        print("nothing to search")        return    }    print(query)}

The purpose of implementing cancelPreviousPerformRequests(withTarget:) is to prevent the continuous calling to the reload() for each change to the search bar (without adding it, if you typed "abc", reload() will be called three times based on the number of the added characters).

The improvement is: in reload() method has the sender parameter which is the search bar; Thus accessing its text -or any of its method/properties- would be accessible with declaring it as a global property in the class.