Guides / Building Search UI / Going further

Conditional Display in InstantSearch iOS

Handling no results

Not all queries lead to results, and it’s important to let users know when this happens. This gives you an opportunity to provide hints on how to adjust the query. This way, you can ensure users don’t leave your website or search using an external search engine.

Display a message

The easiest way to display a fallback message when a query doesn’t return results is to subscribe to the Searcher’s onResponse event and show your “no results” UI whenever the response has no hits.

1
2
3
4
5
6
7
searcher.onResults.subscribe(with: self) { (_, results) in
    if results.hits.isEmpty {
        showNoResultsUI()
    } else {
        hideNoResultsUI()
    }
}

Handling the empty query

By default, InstantSearch iOS always shows you results, even when the query is empty. Depending on your use case and the way you want to build your UI, you may want to only show results when there’s a query.

The Hits widget exposes a showItemsOnEmptyQuery property in the HitsInteractor’s initializer, which defaults to true. When set to false, the widget doesn’t present hits if the query is empty.

1
let hitsInteractor = HitsInteractor<JSON>(showItemsOnEmptyQuery: false)

Handling errors

When an error occurs, you might want to display a specific piece of content to help the user go back to a normal state.

To be notified of errors, subscribe to the Searcher’s onError event.

1
2
3
4
searcher.onError.subscribe(with: self) { (_, args) in
    let (_, error) = args
    debugPrint("Error occured\(error)")
}
Did you find this page helpful?