Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it necessary to use URL bookmarkData to persist file URLs in iOS?

Tags:

ios

nsurl

I'm writing a persistence layer in an iOS app, and came across URL's bookmarkData function. The usage of it looks simple enough, but when I search for discussion of this topic, I only see bookmarkData used in reference to macOS applications.

The files in question are created by the app, not directly by the user, and if they are moved from their directory by the user, then the app can forget about the file.

With those details in mind, should I be persisting the bookmark data in order to access a file URL between launches of the app, or is it safe to save the file URL directly?

like image 428
JGHof Avatar asked Oct 28 '22 23:10

JGHof


1 Answers

If the file is outside of your app's sandbox you must store the bookmark data, you cannot reuse a security scoped URL provided by the UIDocumentPickerVC, per documentation. To get this bookmark data you must access the file using a file presenter/coordinator or UIDocument. Code could look something like this:

func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
    for url in urls {

       //My experience is that your UIDocument subclass needs to be called first 
       //  otherwise bookmarkData() will throw
       //Instead of UIDocument you could call your own file presenter logic
       var doc = MyUIDocument(fileURL: url)
       let bookmarkData = try url.bookmarkData()

       //Store your bookmarkData so you can later resolve a new URL
    }

I hope this helps, as I wasted time with errors when I tried to save bookmark data without working with the file first.

like image 167
James Cramer Avatar answered Nov 15 '22 06:11

James Cramer