Last active
June 6, 2021 16:57
-
-
Save Catherine-K-George/a8c7f9538024a4856cac0fdefcd6fee5 to your computer and use it in GitHub Desktop.
Swift - Dispatch Work Item to show search bar typeahead results
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
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