How do I Customzie the Search Results from PSPDFSearchViewController?

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

A: You need to subclass PSPDFSearchViewController and override -[PSPDFTextSearchDelegate didUpdateSearch:term:newSearchResults:pageIndex:].

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
17
18
19
20
21
22
@interface CustomSearchViewController : PSPDFSearchViewController
@end

@implementation CustomSearchViewController

- (void)didUpdateSearch:(PSPDFTextSearch *)textSearch term:(NSString *)searchTerm newSearchResults:(NSArray<PSPDFSearchResult *> *)searchResults pageIndex:(PSPDFPageIndex)pageIndex {
    // 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 didUpdateSearch:textSearch term:searchTerm newSearchResults:filteredSearchResults pageIndex:pageIndex];
}

@end