Created
August 13, 2018 01:13
-
-
Save Yoloabdo/6f45e38a2f46c57095c5f124da05dd7c to your computer and use it in GitHub Desktop.
Throttling Searchbar ios swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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