Detecting If Annotations Have Changed on iOS

PSPDFKit allows you to edit and create annotations if your license includes this component. You can detect changes to the underlying data models by listening to the following notifications.

Notification Description
.PSPDFAnnotationsAdded Sent when new annotations are added to the default PDFFileAnnotationProvider. Object posting is an array of new Annotation(s).
.PSPDFAnnotationsRemoved Sent when new annotations are removed from the default PDFFileAnnotationProvider. Object posting is an array of removed Annotation(s).
.PSPDFAnnotationChanged Internal events to notify the annotation providers when annotations are being changed. Send only from main thread. Don’t call save during a change notification.

Here’s an example of listening to changes of the contents in the note annotation controller:

// Start listening to the annotation's change notification.
NotificationCenter.default.addObserver(self, selector: #selector(annotationChangedNotification(notification:)), name: .PSPDFAnnotationChanged, object: nil)

func annotationChangedNotification(notification: Notification) {
    // Check if we need to rerender ourselves.
    let changedAnnotation = notification.object as! Annotation
    if annotation == changedAnnotation, let keyPaths = notification.userInfo?[PSPDFAnnotationChangedNotificationKeyPathKey] as? [String] {
        if keyPaths.count > 1 || keyPaths.first != "contents" {
            updateImage(animated: true)
        }
    }
}
// Start listening to the annotation's change notification.
[NSNotificationCenter.defaultCenter addObserver:self selector:@selector(annotationChangedNotification:) name:PSPDFAnnotationChangedNotification object:nil];

- (void)annotationChangedNotification:(NSNotification *)notification {
    // Check if we need to rerender ourselves.
    if ([self.annotation isEqual:notification.object]) {
        NSArray *keyPaths = notification.userInfo[PSPDFAnnotationChangedNotificationKeyPathKey];
        if (keyPaths.count > 1 || ![keyPaths.firstObject isEqual:@"contents"]) {
            [self updateImageAnimated:YES];
        }
    }
}

In PSPDFKit, annotations are usually created using AnnotationStateManager. If you create a drawing, the state manager is in the draw mode and will cache drawn lines until you exit the draw state, which will, in turn, cause an InkAnnotation object to be created. After creation, an undo operation will remove the entire annotation — but while you’re in the drawing mode, undo/redo operates on a finer level, affecting one stroke at a time.

If you change annotations, make sure to also post appropriate change notifications. See our guide on the annotation object model for details.