iOS 16中如何使用UIDocumentPickerViewController导入文件
在UIKit中使用UIDocumentPickerViewController导入PDF的非弃用方案
核心替代思路
iOS 14及后续版本,官方推荐使用基于UIDocumentPickerConfiguration的初始化器,配合UTType类型安全常量指定文档类型,替代已弃用的documentTypes:in:初始化方式。
具体实现步骤
导入必要框架
需要引入UniformTypeIdentifiers框架来使用系统定义的文档类型常量:import UIKit import UniformTypeIdentifiers配置并弹出文档选择器
通过UIDocumentPickerConfiguration配置选择规则,再初始化选择器并展示:func showPDFPicker() { let config = UIDocumentPickerConfiguration() // 限定仅可选择PDF文件 config.allowedContentTypes = [UTType.pdf] // 设置选择模式为导入(也可根据需求选择.open/.move等模式) config.mode = .import let picker = UIDocumentPickerViewController(configuration: config) picker.delegate = self // iPad端需设置popover锚点,比如绑定触发按钮 // picker.popoverPresentationController?.sourceView = yourTriggerButton present(picker, animated: true) }实现代理处理选中文件
遵守UIDocumentPickerDelegate协议,处理用户选中的PDF文件:extension YourViewController: UIDocumentPickerDelegate { func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) { guard let pdfTempURL = urls.first else { return } // 导入模式下的URL是临时沙盒路径,需复制到应用私有目录留存 let docDir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] let targetURL = docDir.appendingPathComponent(pdfTempURL.lastPathComponent) do { // 先移除已存在的同名文件 if FileManager.default.fileExists(atPath: targetURL.path) { try FileManager.default.removeItem(at: targetURL) } try FileManager.default.copyItem(at: pdfTempURL, to: targetURL) // 后续可读取targetURL路径下的PDF文件进行展示或处理 print("PDF已导入至:\(targetURL)") } catch { print("PDF导入失败:\(error.localizedDescription)") } } func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) { dismiss(animated: true) } }
关键注意点
- 类型安全优势:
UTType.pdf是系统提供的类型安全常量,避免了手动编写UTI字符串可能出现的错误。 - 选择模式差异:
.import会复制文件到应用临时目录,需手动迁移至私有目录;.open则直接访问原文件(依赖文件提供者支持),根据业务需求选择。 - iPad适配:iPad上必须为选择器的
popoverPresentationController设置锚点(如按钮、视图),否则选择器无法正常展示。
内容的提问来源于stack exchange,提问作者Roy0Anonymous
相关产品推荐
相关产品推荐

