Skip to content

Instantly share code, notes, and snippets.

@Yoloabdo
Created August 13, 2018 01:13
Show Gist options
  • Select an option

  • Save Yoloabdo/6f45e38a2f46c57095c5f124da05dd7c to your computer and use it in GitHub Desktop.

Select an option

Save Yoloabdo/6f45e38a2f46c57095c5f124da05dd7c to your computer and use it in GitHub Desktop.
Throttling Searchbar ios swift
class SearchViewController: UIViewController, UISearchBarDelegate {
// We keep track of the pending work item as a property
private var pendingRequestWorkItem: DispatchWorkItem?
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
// Cancel the currently pending item
pendingRequestWorkItem?.cancel()
// Wrap our request in a work item
let requestWorkItem = DispatchWorkItem { [weak self] in
self?.resultsLoader.loadResults(forQuery: searchText)
}
// Save the new work item and execute it after 250 ms
pendingRequestWorkItem = requestWorkItem
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(250),
execute: requestWorkItem)
}
}
// Written by John sundell https://www.swiftbysundell.com/posts/a-deep-dive-into-grand-central-dispatch-in-swift
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment