Pick UIDocument automatically in UIDocumentBrowserVC

本小妞迷上赌 提交于 2020-01-15 10:24:11

问题


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)



来源:https://stackoverflow.com/questions/48750600/pick-uidocument-automatically-in-uidocumentbrowservc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!