Detecting User Input in PDF Form Fields on iOS
Form elements are based on annotations, so you can use Notification.Name.PSPDFAnnotationChanged
to listen for user input in forms:
// Start listening to the change notifications from all annotations. NotificationCenter.default.addObserver(self, selector: #selector(annotationChanged(_:)), name: .PSPDFAnnotationChanged, object: nil) @objc func annotationChanged(_ notification: Notification) { // Make sure it was a text field that changed. guard let annotation = notification.object as? TextFieldFormElement else { return } // Make sure that the annotation is in the currently handled document. guard annotation.document === self.document else { return } // Make sure that the contents, and not the style, changed. guard let keyPaths = notification.userInfo?[PSPDFAnnotationChangedNotificationKeyPathKey] as? [String], keyPaths.contains(#keyPath(Annotation.contents)) else { return } // Handle the change. print("Text field content changed: \(annotation.contents!)") }
// Start listening to the change notifications from all annotations. [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(annotationChanged:) name:PSPDFAnnotationChangedNotification object:nil]; - (void)annotationChanged:(NSNotification *)notification { // Extract the notification content for further use. PSPDFAnnotation *annotation = (PSPDFAnnotation *)notification.object; NSArray<NSString *> *keyPaths = notification.userInfo[PSPDFAnnotationChangedNotificationKeyPathKey]; // Make sure it was a text field that changed. if (![notification.object isKindOfClass:PSPDFTextFieldFormElement.class]) { return; } // Make double sure that the annotation is in the currently handled document. // Direct pointer comparison used on purpose. if (annotation.document != self.document) { return; } // Make sure that the contents, and not the style, changed. if (![keyPaths containsObject:@"contents"]) { return; } // Handle the change. NSLog(@"Text field content changed: %@", annotation.contents); }
The above technique can also be used to listen for changes in other types of form fields.