在UIDocumentBrowserVC中自动选择UIDocument [英] Pick UIDocument automatically in UIDocumentBrowserVC
问题描述
我正在使用uidocumentbrowservc
,并希望以编程方式选择UIDocument
.就我而言,这是因为我想自动加载上次使用的UIDocument
来节省用户启动时间,因为我的应用很少更改文档.
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.
我幼稚的方法是将上次使用的URL
存储在UserDefaults
中.然后在uidocumentbrowservc
的viewDidLoad()
中调用presentDocument(at: URL)
.但这是行不通的.当我打电话给URL.checkResourceIsReachable()
时,我得到了错误:
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代码= 257文件"myFile"无法 因为您没有查看权限而被打开."
Error Domain=NSCocoaErrorDomain Code=257 "The file "myFile" couldn’t be opened because you don’t have permission to view it."
文件路径为:
/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.
推荐答案
您不能仅保存URL.您还需要保存UIDBVC授予您的沙盒扩展.保存一个书签而不是URL可以做到这一点.此外,如果用户移动文件(例如,在其他设备上的iCloud Drive内部重命名),书签将继续起作用.普通网址不会.
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.
使用选项.withSecurityScope和URLByResolvingBookmarkData:options:relativeToURL:bookmarkDataIsStale:error:检查URL的bookmarkData(options:includesResourceValuesForKeys:relativeTo:)(然后不要忘记对结果URL调用start/stopAccessing)
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)
这篇关于在UIDocumentBrowserVC中自动选择UIDocument的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!