Action handling in PDFView
With iOS 11, Apple introduced a new PDFKit
to replace old API used for rendering PDF files. You can use this new API in Tabris.js 3.6 where we introduced PdfView
.
The new framework not only renders PDF documents but also allows interacting with them. Some of the annotations are handled by default (like text fields or checkboxes), where others need handling by the developer (for example, signing fields). In both cases, you can get a callback when a user interacts with such an annotation.
Let’s create PDFView
and add it to the view hierarchy:
1 2 3 4 5 6 7 8 9 |
import UIKit class ViewController: UIViewController { override func loadView() { let pdfView = PDFView() view = pdfView } } |
Next we will load PDF document:
1 2 3 4 5 6 |
override func viewDidLoad() { super.viewDidLoad() let url = URL(string: "http://localhost:3000/doc.pdf") let document = PDFDocument.init(url: url) self.document = document } |
In order to handle an action we need to register for a NSNotification.Name.PDFViewAnnotationHit
notification in viewDidLoad
:
1 |
NotificationCenter.default.addObserver(self, selector: #selector(annotationHit(notification:)), name: NSNotification.Name.PDFViewAnnotationHit, object: nil) |
Now let’s implement the handler method:
1 2 3 4 |
@objc func annotationHit(notification: Notification) { let annotationInfo = notification.userInfo!["PDFAnnotationHit"] as! PDFAnnotation print("\(annotationInfo)") } |
This will print details about touched annotation. Depending on the type of the widget, it will contain things like text, if it’s a text input, or a checkbox state if an annotation is a checkbox. From this point on, we can start building custom handling for annotations that we need to support.
While Apple’s online documentation provides a lot of details about classes in PDFKit
, there is, even more, to discover when going through headers of these classes in Xcode. I encourage you to experiment with PDFKit
to find more undocumented features.
Feedback is welcome!
Want to join the discussion?Feel free to contribute!