Skip to content

Instantly share code, notes, and snippets.

@Catherine-K-George
Last active June 6, 2021 16:57
Show Gist options
  • Save Catherine-K-George/a8c7f9538024a4856cac0fdefcd6fee5 to your computer and use it in GitHub Desktop.
Save Catherine-K-George/a8c7f9538024a4856cac0fdefcd6fee5 to your computer and use it in GitHub Desktop.
Swift - Dispatch Work Item to show search bar typeahead results
import UIKit
class SearchViewController: UIViewController {
private var searchWorkItem: DispatchWorkItem?
override func viewDidLoad() {
super.viewDidLoad()
}
private func search(withText text: String) {
searchWorkItem?.cancel()
let task = DispatchWorkItem { [weak self] in
guard let self = self else { return }
self.performSearch(with: text)
}
searchWorkItem = task
// Excute the workitem after 0.3 seconds.
DispatchQueue.main.asyncAfter(deadline: .now()+0.3, execute: task)
}
private func performSearch(with text: String) {
// Make API request with search text
}
}
extension SearchViewController: UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
search(withText: searchText)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment