Concepts / Building Search UI / Conditional display
May. 10, 2019

Conditional Display

Handling no results

When no results are found you might want to display some specific content helping the user go back to a search that was successful.

Empty View

The Hits widget implements an empty view mechanism to display an alternative View if there are no results to display. For that, you can use the HitsTableViewDataSource or the HitsCollectionViewDataSource method:

  • viewForNoResults(in tableView: UITableView) -> UIView
  • viewForNoResults(in collectionView: UICollectionView) -> UIView.
1
2
3
4
5
6
7
8
9
10
    func viewForNoResults(in tableView: UITableView) -> UIView {
        let noDataLabel: UILabel = UILabel(frame: CGRect(x: 0, y: 0,
                                                         width: tableView.bounds.size.width,
                                                         height: tableView.bounds.size.height))
        noDataLabel.text          = "NO RESULTS!"
        noDataLabel.textColor     = UIColor.black
        noDataLabel.textAlignment = .left

        return noDataLabel
    }

Handling errors

When an error occurred you might want to display some specific content helping the user go back to a search that was successful.

To help you with that, we offer a few APIs:

Notification

The Searcher class in InstantSearch.shared.getSearcher() emits notifications through NSNotificationCenter on error events:

  • Searcher.ErrorNotification when an erroneous response is received

Closure

The Searcher will call your result handler after each request, when the response is received, unless the request has been cancelled (e.g. because newer results have already been received). Your result handler will check for errors:

1
2
3
4
5
6
7
8
9
10
func handleResults(results: SearchResults?, error: Error?, userInfo: [String: Any]) {
    if let error = error {
      // deal with error
    }
    self.hits = results.hits
    self.tableView.reloadData()
}

let searcher = InstantSearch.shared.getSearcher()
searcher.addResultHandler(handleResults)

Handling empty query

By default InstantSearch iOS will always show you results even when the query is empty. In some case you may want to hide the results on the empty query.

To help you with that, the Hits widget exposes a property showItemsOnEmptyQuery. When false, it will display an empty hits widget when there is no query text entered by the user. It defaults to true.

1
2
3
4
5
hitsTableWidget.showItemsOnEmptyQuery = false
hitsTableWidget.showItemsOnEmptyQuery = true

hitsCollectionWidget.showItemsOnEmptyQuery = false
hitsCollectionWidget.showItemsOnEmptyQuery = true

Did you find this page helpful?