如何使用UIDocumentPickerViewController打开根目录文件夹
让UIDocumentPickerViewController默认显示根目录
要让UIDocumentPickerViewController打开时直接定位到你截图里的系统文件根目录,你之前的问题是没能获取到正确的根目录URL,以下是可行的解决方案:
正确设置根目录URL的方式
直接通过FileManager获取系统根目录的URL,并赋值给directoryURL即可,代码示例:
// 创建文档选择器实例,允许选择所有类型文件 let documentPicker = UIDocumentPickerViewController(documentTypes: ["public.item"], in: .open) // 获取系统文件根目录URL if let rootDirectoryURL = FileManager.default.url(for: .rootDirectory, in: .userDomainMask, appropriateFor: nil, create: false) { documentPicker.directoryURL = rootDirectoryURL } // 设置代理并弹出选择器 documentPicker.delegate = self present(documentPicker, animated: true)
为什么你之前的方法无效?
- 你尝试设置的是自己APP沙盒内的
documentDirectory,这只是APP私有目录,并非系统文件的根目录。 - 手动替换URL scheme为
shareddocuments://的做法不规范,且没有指向正确的根路径,自然无法定位到目标目录。
如果你的项目适配iOS 14及以上版本,也可以用更简洁的API初始化选择器:
let documentPicker = UIDocumentPickerViewController(forOpeningContentTypes: [.item], asCopy: false) if let rootURL = FileManager.default.url(for: .rootDirectory, in: .userDomainMask, appropriateFor: nil, create: false) { documentPicker.directoryURL = rootURL } documentPicker.delegate = self present(documentPicker, animated: true)
内容的提问来源于stack exchange,提问作者joemiddletone
相关产品推荐
相关产品推荐

