Stats
About this widget
Each search results comes with a SearchStats
structure containing metadata that you might display in your search experience.
The following information is available within SearchStats
:
hitsPerPage
: Number of hits per page.totalHitsCount
: Total number of hits.pagesCount
: Total number of pages.page
: Current page.processingTimeMS
: Processing time of the request (in ms).query
: Query text that produced these results.
To add Stats
to your search experience, use these components:
Searcher
: TheSearcher
that handles your searches.StatsInteractor
: The logic applied to the stats.StatsController
: The controller that interfaces with a concrete stats view.
InstantSearch provides two StatsController
s:
LabelStatsController
: presents metadata in UILabel in the form of text.AttributedLabelStatsController
: presents metadata in UILabel in the form of attributed text.
The format in which metadata appears in StatsController
is defined in the presenter closure provided while connecting the controller with Interactor
.
Examples
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
let searcher: SingleIndexSearcher = .init(appID: "YourApplicationID",
apiKey: "YourSearchOnlyAPIKey",
indexName: "YourIndexName")
let statsInteractor: StatsInteractor = .init()
let labelStatsController: LabelStatsController = LabelStatsController(label: UILabel())
override viewDidLoad() {
super.viewDidLoad()
// Connect stats interactor with searcher
statsInteractor.connectSearcher(searcher)
// Connect stats interactor with controller providing presenting closure
statsInteractor.connectController(labelStatsController) { stats -> String? in
guard let stats = stats else {
return "Error occured"
}
return "\(stats.totalHitsCount) hits in \(stats.processingTimeMS) ms"
}
// Launch the search
searcher.search()
}
Customize your view
The controllers provided by default, like the LabelStatsController
work well when you want to use native UIKit with their default behavior.
If you want to use another component (other than a UILabel
) such as a UITextView
, a 3rd party view, or want to introduce some custom behavior to the already provided UIKit component, you can create your own controller conforming to the StatsTextController
protocol.
Protocol
func setItem(_ item: String?)
:
Function called when new metadata are received.
Example
1
2
3
4
5
6
7
8
9
10
11
12
13
public class LabelStatsController: StatsTextController {
public let label: UILabel
public init (label: UILabel) {
self.label = label
}
public func setItem(_ item: String?) {
label.text = item
}
}