How do I Customzie the Search Results from SearchViewController?

Q: How do I Customzie the Search Results from SearchViewController?

A: You need to subclass SearchViewController and override TextSearchDelegate.didFinish(_:term:searchResults:isFullSearch:pageTextFound:).

In the example below, we filter out the matching search results that are not at the begining of the word. For example if the search term is “PDF”, we match “PDFs”, but we will not match “PSPDFKit”:

Copy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class CustomSearchViewController: SearchViewController {

    override func didFinish(_ textSearch: TextSearch, term searchTerm: String, searchResults: [SearchResult], isFullSearch: Bool, pageTextFound: Bool) {
        // Filter out the matching search results that are not at the begining of the word.
        var filteredSearchResults = [SearchResult]()
        searchResults.forEach { searchResult in
            let words = searchResult.previewText.components(separatedBy: .punctuationCharacters)
            words.forEach { word in
                if word.lowercased().hasPrefix(searchTerm.lowercased()) {
                    filteredSearchResults.append(searchResult)
                }
            }
        }
        super.didFinish(textSearch, term: searchTerm, searchResults: filteredSearchResults, isFullSearch: isFullSearch, pageTextFound: pageTextFound)
    }
}
Copy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@interface CustomSearchViewController : PSPDFSearchViewController
@end

@implementation CustomSearchViewController

- (void)didFinishSearch:(PSPDFTextSearch *)textSearch term:(NSString *)searchTerm searchResults:(NSArray<PSPDFSearchResult *> *)searchResults isFullSearch:(BOOL)isFullSearch pageTextFound:(BOOL)pageTextFound {
    // Filter out the matching search results that are not at the begining of the word.
    NSMutableArray<PSPDFSearchResult *> *filteredSearchResults = [NSMutableArray new];
    [searchResults enumerateObjectsUsingBlock:^(PSPDFSearchResult * _Nonnull searchResult, NSUInteger idx, BOOL * _Nonnull stop) {
        NSArray <NSString *> *words = [searchResult.previewText componentsSeparatedByCharactersInSet:[NSCharacterSet punctuationCharacterSet]];
        for (NSString *word in words) {
            if ([word.lowercaseString hasPrefix:searchTerm.lowercaseString]) {
                [filteredSearchResults addObject:searchResult];
            }
        }
    }];
	
    // Call super with the new filtered search results.
    [super didFinishSearch:textSearch term:searchTerm searchResults:filteredSearchResults isFullSearch:isFullSearch pageTextFound:pageTextFound];
}

@end