Making a PDF Capture App - Part 2

Last time, we left off with a cliff hanger. What was wrong with our PDF editing?

Answer: our changes didnā€™t persist. The fileWrapper function that saves the app never got called. Hmmm.

If you remember our text editing app, the string we passed in changed. And a String is a value type. In fact, the whole document is a value type! This means when we change something, the whole document changes, and thatā€™s when the document get saved.

But the PDFDocument weā€™re using isnā€™t a struct or a value type. Itā€™s a reference type. So when we change it, it doesnā€™t register for the whole document.

So how do we change it? I made a little hack. I give it something that can be changed, and when changed, triggers the save.

I added a simple Boolean to the document called ā€œsaveTrigger.ā€

And in my ContentView, I simply toggle the value on the document (the value doesn't matter; only changing the value matters).

But I donā€™t only want to save the view when Iā€™m on the ContentView. So I have ContentView subscribe to the publisher of a StateObject I call PDFManager.

pdfmanager.png

And now my ContentView looks like this

contentview.png

Persistence problem solved.

Now, before we get to the fun stuff, I have another setup issue I need to solve. I want to know if Iā€™m looking at a newly created, blank PDF, or if the user has just selected a previously created PDF. Well, after searching around, there donā€™t seem to be any definitive answers on knowing whether a PDF has no content. So, when we create the PDF, letā€™s just leave some metadata that weā€™ve created a blank PDF!

Now, PDFKit wonā€™t let you leave just any metadata with PDFDocument. You need to use a predefined PDFDocumentAttribute. The most useful one for our purposes is called keywordsAttribute. So weā€™ll set a keyword to value that is unlikely to be used elsewhere as a keyword, so that someone doesnā€™t accidentally use our keyword.

So now our init for PDFTrapperDocument looks like this:

new_init.png

And we add a blankness property and a way to set it to not blank like this:

is_blank_setnotblank.png

Now we can test whether our PDF is marked as blank or not!

is_blank_test.png

Try it out and youā€™ll see that it starts as blank and after about 3 seconds the edit happens and the document says it is not blank. Success!

(BTW, at this point, donā€™t open an existing PDF that you donā€™t want edited, or it will get edited!)

is_blank_screen.png
is_not_blank.png

Cool cool. Next week we can get to the fun stuff. Actually adding the document scanner! Stay tuned. Sign up here if you're interested in checking out the beta when it's ready :) And for any other comments, say hi to me on Twitter at wattmaller1.

Previous
Previous

Making PDF Capture App - Part 3

Next
Next

Making a PDF Capture App - Part 1