I try to use search controller on my tableview on this link. If user pause typing on the searchbar for 0.3 sec then it will fire fetch method.
I know how to fire method on every change in search bar using updateSearchResultsForSearchController
, but it wasn't I want. Then I use search bar delegate searchBarSearchButtonClicked
, but it fired only when search button on keyboard was pressed.
What I want is fire a method like when user stop typing for 0.3 sec. Is there any way to do this? Or am I going wrong with the concept of using search controller + fetch data?
Any help would be appreciated.
You can use an NSTimer
to achieve this functionality. Simply start or restart the timer in updateSearchResultsForSearchController
. Once the user stops typing long enough for the timer to fire, you can perform the search:
var searchTimer: NSTimer?
func updateSearchResultsForSearchController(searchController: UISearchController) {
self.searchTimer?.invalidate()
self.searchTimer = NSTimer.scheduledTimerWithTimeInterval(0.3,
target: self,
selector: #selector(ViewController.searchTimerExpired),
userInfo: nil,
repeats: false)
}
}
@objc func searchTimerExpired() {
self.searchTimer = nil
// Do your search
}