forked from algolia/instantsearch-ios
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathQuerySuggestionsRecentSearches.SearchViewController.swift
79 lines (64 loc) · 2.67 KB
/
QuerySuggestionsRecentSearches.SearchViewController.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
//
// SearchViewController.swift
// Examples
//
// Created by Vladislav Fitc on 03/11/2021.
//
import Foundation
import InstantSearch
import UIKit
enum QuerySuggestionsAndRecentSearches {
class SearchViewController: UIViewController {
let searchController: UISearchController
let searchBoxConnector: SearchBoxConnector
let textFieldController: TextFieldController
let hitsSearcher: HitsSearcher
let hitsInteractor: HitsInteractor<QuerySuggestion>
let searchResultsController: SearchResultsController
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
hitsSearcher = .init(client: .instantSearch,
indexName: .instantSearchSuggestions)
searchResultsController = .init()
hitsInteractor = .init()
searchController = .init(searchResultsController: searchResultsController)
textFieldController = .init(searchBar: searchController.searchBar)
searchBoxConnector = .init(searcher: hitsSearcher,
controller: textFieldController)
hitsInteractor.connectSearcher(hitsSearcher)
hitsInteractor.connectController(searchResultsController)
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
searchResultsController.onSelection = { [weak self] in
self?.searchBoxConnector.interactor.query = $0
}
searchController.searchBar.searchTextField.addTarget(self, action: #selector(textFieldSubmitted), for: .editingDidEndOnExit)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
configureUI()
hitsSearcher.search()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
searchController.isActive = true
}
func configureUI() {
title = "Recent Searches & Suggestions"
view.backgroundColor = .systemBackground
searchController.hidesNavigationBarDuringPresentation = false
searchController.showsSearchResultsController = true
searchController.automaticallyShowsCancelButton = false
navigationItem.searchController = searchController
}
@objc func textFieldSubmitted() {
guard let text = searchController.searchBar.text else { return }
if let alreadyPresentIndex = searchResultsController.recentSearches.firstIndex(where: { $0 == text }) {
searchResultsController.recentSearches.remove(at: alreadyPresentIndex)
}
searchResultsController.recentSearches.insert(text, at: searchResultsController.recentSearches.startIndex)
searchResultsController.tableView.reloadData()
}
}
}