Index and Search PDFs Using iOS Spotlight
PSPDFKit’s PDFLibrary
implements a full-text-search engine based on a SQLite database that can also optionally index documents with Spotlight, so the user can search for documents (and their text) from the native device search. To enable this, set up PDFLibrary
, and set the spotlightIndexingType
property before calling PDFLibrary.updateIndex(completionHandler:)
. This can be set to one of the following:
-
.disabled
— documents are not indexed in Spotlight -
.enabled
— documents are indexed in Spotlight, but their text is not -
.enabledWithFullText
— documents are indexed in Spotlight with their full text
Retrieving Documents from Spotlight
When the user taps on a searchable item from your app in Spotlight search results, your app delegate’s application(_:continue:restorationHandler:)
method is called.
In your implementation of this method, call PDFLibrary.fetchSpotlightIndexedDocument(for:completionHandler:)
to retrieve the document, if any:
func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([Any]?) -> Void) -> Bool { guard let library = PSPDFKit.SDK.shared.library else { logError("Unable to get shared PDFLibrary instance to continue user activity.") return false } library.fetchSpotlightIndexedDocument(for: userActivity) { guard let document = $0 else { return } // Open the document in a `PDFViewController`. } return true }
- (BOOL)application:(NSApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray *restorableObjects))restorationHandler { PSPDFLibrary *library = PSPDFKitGlobal.sharedInstance.library; if (!library) { // FTS feature isn't enabled in your license. return NO; } [PSPDFKitGlobal.sharedInstance.library fetchSpotlightIndexedDocumentForUserActivity:userActivity completionHandler:^(PSPDFDocument *document) { if (!document) { return; } // Open the document in a `PSPDFViewController`. }]; return YES; }