Reputation: 4962
I have a textfield, which fetches data from an API everytime the textField text changes, and updates the table.
override func viewDidLoad() {
super.viewDidLoad()
searchTextField.addTarget(self, action: #selector(textFieldDidChange), for: UIControlEvents.editingChanged)
}
func textFieldDidChange() {
let queryString = self.searchTextField.text
SearchWSFacade.getSearchResults(queryString: queryString) {
(error) in
if (error == nil) {
self.tableView.reloadData()
}
}
}
This works wonderfully, only if the user types slow (allows data to load before typing next character). If the user types fast, we run into issues, because of multiple calls to reloadData.
This could be solved if I cancelled the completion handler when searching when a previous search is occurring. How do I do this? Or is there a better solution?
Upvotes: 1
Views: 268
Reputation: 5554
You could set a simple flag in the UIViewController containing the text field - busyCallingAPI
, perhaps - set it true when you start the API call, set it false in the completion handler, and in textFieldDidChange
only make the call if busyCallingAPI
is false
Upvotes: 0
Reputation: 150665
If you use Operations, you can set up dependencies so that one doesn't start until the next one completes. And, unlike blocks, Operations can be cancelled.
Upvotes: 1