Search PDF Annotations in iOS

PSPDFKit offers many different ways to search a document, including using a highly customizable UI component. The search functionality also supports searching for text contained in PDF annotations as comments and replies.

Before reading this guide any further, please check out the Text Search guide to familiarize yourself with the text search APIs that form the basis of searching for annotation results.

Searching via PSPDFViewController

PSPDFKit will automatically search for text contained in annotations when using the built-in search UI via the provided search bar button item or when displaying the search UI programmatically using search(for:options:sender:animated:). This behavior is controlled using the SearchViewController.searchableAnnotationTypes property, which defaults to all annotation types except links.

If you’d like to customize this behavior to limit searching to a different set of annotation types or to disable annotation search completely, you can use PSPDFKit’s class override system to subclass SearchViewController and override the property value.

The example below shows how to disable annotation search:

// Set the override when creating your PDF controller.
let controller = PDFViewController(document: document) {
    $0.overrideClass(SearchViewController.self, with: CustomSearchViewController.self)
}

// Overrides the class definition.
private class CustomSearchViewController: SearchViewController {
    override init(document: Document?) {
        super.init(document: document)
        // Disable annotation search.
        searchableAnnotationTypes = []
    }
}

Searching Manually

In contrast to the built-in UI, annotations won’t be searched by default when using the TextSearch class to search a PDF programmatically. You can change this behavior by setting the TextSearch.searchableAnnotationTypes property to a set of annotation types before triggering search via calling search(for:). To receive search results, implement TextSearchDelegate on the receiving object and set the text search object’s delegate to your object.

The didUpdate(_:term:searchResults:pageIndex:) delegate will be notified of search results within annotations alongside text results from the page content. Both are received in the form of SearchResult objects, whereby annotation results can be identified by having an annotation reference associated with the SearchResult.annotation property.

❗ Important: You need to retain the text search object while the search is running. Otherwise, any running search will automatically be canceled and your delegate won’t get called.