My solution is composed of many other SO posts, and of the official Apple documentation.
It creates a view with a search bar in the UINavigationBar (so you need your NavigationController to be embeded, but you may change some line to avoid this).
You can then select this SearchBar and it will dim the ViewController,
then after typing some search it will autocomplete, and when tapping SearchButton start the actual search.
class ViewController: UISearchResultsUpdating, UISearchControllerDelegate, UISearchBarDelegate {
//Our SearchController
var searchController: UISearchController!
override func viewDidLoad() {
super.viewDidLoad()
let src = SearchResultTVC() //A simple UiTableViewController I instanciated in the storyboard
// We instanciate our searchController with the searchResultTCV (we he will display the result
searchController = UISearchController(searchResultsController: src)
// Self is responsible for updating the contents of the search results controller
searchController.searchResultsUpdater = self
self.searchController.delegate = self
self.searchController.searchBar.delegate = self
// Dim the current view when you sélect eh search bar (anyway will be hidden when the user type something)
searchController.dimsBackgroundDuringPresentation = true
// Prevent the searchbar to disapear during search
self.searchController.hidesNavigationBarDuringPresentation = false
// Include the search controller's search bar within the table's header view
navigationItem.titleView = searchController.searchBar
definesPresentationContext = true
}
Then the other fonction is the one who is called when the text in the searchbar is modified :
func updateSearchResultsForSearchController(searchController: UISearchController) {
// If dismissed then no update
if !searchController.active {
return
}
// Write some code for autocomplete (or ignore next fonction and directly process your data hère and siplay it in the searchResultTCV)
}
My choice is to leave updateSearchResultsForSearchControlller() do the autocomplete, and then load the results when the user press search, so I have this last fonction :
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
if let search = searchController.searchBar.text {
// Load your results in searchResultTVC
}
}