Pick UIDocument automatically in UIDocumentBrowser

2019-08-12 06:40发布

问题:

I am using a uidocumentbrowservc and want to pick a UIDocument programmatically. In my case it is because i want to automatically load the last used UIDocument to save the user some time on launch, as my app seldom changes documents.

My naive approach is to store last used URL in UserDefaults. Then in the viewDidLoad() of my uidocumentbrowservc I call presentDocument(at: URL). But it doesn't work. And when i call URL.checkResourceIsReachable() I get the error:

Error Domain=NSCocoaErrorDomain Code=257 "The file “myFile” couldn’t be opened because you don’t have permission to view it."

The file path is:

/private/var/mobile/Library/Mobile Documents/com~apple~CloudDocs/MyApp/myFile.

As far as I understand, I don't have access to it because it is not in my sandbox (It could be anywhere the user saves it?).

Any suggestions? I am sure there exist better ways to do this.

回答1:

You cannot just save the URL. You need to save the sandbox extension granted to you by UIDBVC as well. Saving a bookmark instead of the URL will do that. In addition, a bookmark will keep working if the user moves the file (e.g. renamed inside iCloud Drive on a different device). A plain URL will not.

Check out URL’s bookmarkData(options:includingResourceValuesForKeys:relativeTo:) with options .withSecurityScope and URLByResolvingBookmarkData:options:relativeToURL:bookmarkDataIsStale:error: (and then don’t forget to call start/stopAccessing on the resulting URL)