Open the last used document on App startup

Did you ever want your app to open the last used document on startup? Well, that’s not too difficult on macOS. In your NSDocumentController subclass you have the array of recentDocumentURLs, and on startup you can try to open the first member if it exists.

But on iOS it’s a little bit more tricky. There is no such array as on macOS. So we have to mimic it by ourself.

This is a review of my post 2 years ago: UIDocumentBrowserViewController and External Storage

If you have a document based app on iOS you probably want it to be able to open documents outside the sandbox. To do so you may have to set some flags in the info file of the app, esp.:

Application supports iTunes file sharing YES
Supports opening documents in place YES

And if you want your app to store documents on the iCloud you have to give the corresponding entitlement in “Signing & Capabilities”:

iCloud: ✅ iCloud documents

Well, now we can store the last opened document URL in our User Defaults whenever we open or create a new document:

We should never store a path or something like that if we want to re-open a document later. Instead, we create a bookmark of the URL and store that data object in the User Defaults.

Now we can try to open that stored URL on startup of our app, e.g. at viewDidLoad of our document controller:

First we have to decode the bookmark stored in the User Defaults and create an URL from it. If that’s ok we can open the document. If we do not succeed we have to present an empty document or show the document browser to select another one. If the bookmark is not valid any more we can try to create a new one from the supplied URL.

That all works fine for locally stored or iCloud documents. But, funny enough, for documents on other cloud services (e.g. on Synology NAS Servers) this mechanism fails. I’ve been struggling with this issue for years now and finally gave up to solve it.

Then, recently, I stumbled over this post on Stackoverflow.

It seemed to be a little bit unrelated but I gave it a try if this trick works for me as well. And yes, asking the file manager whether the file exists on that external storage seems to force a download of the file. And I can open it despite the fact that the file manager signals that the file is not present. The file coordinator mentioned in this post is already implemented in the document classes of iOS. Asking the file manager for the file seems to make the trick. I would like to count that as bug.

But anyway, now I’m happy with this workaround and can re-open the last used document on iOS even if it is stored on some other cloud service.

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht.