Xcode 9/iOS 11:如何让DocumentBrowserViewController展示自建PDF文件?
看起来你已经走了大部分流程,生成PDF和存储都没问题,卡在了DocumentBrowser选完文件后显示的环节。我之前也遇到过类似情况,主要是Xcode模板默认的DocumentViewController是为文本类文档设计的,得调整下适配PDF。下面一步步来解决:
1. 修正DocumentViewController的PDF加载逻辑
模板生成的Document类(比如MyDocument.swift)默认是处理文本数据的,完全不适合PDF。其实我们不需要解析PDF内容,直接用WKWebView加载文件URL就行,甚至可以简化掉UIDocument的复杂逻辑(如果不需要版本管理、iCloud同步这些的话)。
修改你的DocumentViewController代码:
import UIKit import WebKit class DocumentViewController: UIViewController { var documentURL: URL? // 直接用URL代替UIDocument,更简单 private var webView: WKWebView! override func viewDidLoad() { super.viewDidLoad() // 初始化WKWebView并铺满整个视图 webView = WKWebView(frame: view.bounds) webView.autoresizingMask = [.flexibleWidth, .flexibleHeight] view.addSubview(webView) // 加载PDF文件 if let url = documentURL { webView.loadFileURL(url, allowingReadAccessTo: url.deletingLastPathComponent()) } } }
然后在DocumentBrowserViewController的代理方法里,直接传文件URL给DocumentViewController,而不是用默认的UIDocument:
extension DocumentBrowserViewController: UIDocumentBrowserViewControllerDelegate { func documentBrowser(_ controller: UIDocumentBrowserViewController, didPickDocumentsAt documentURLs: [URL]) { guard let sourceURL = documentURLs.first else { return } // 实例化DocumentViewController并传入PDF URL let documentVC = DocumentViewController() documentVC.documentURL = sourceURL documentVC.title = sourceURL.lastPathComponent // 用导航控制器push或者present let navigationVC = UINavigationController(rootViewController: documentVC) present(navigationVC, animated: true) } }
2. 确保Info.plist配置正确的PDF支持
Xcode模板可能没默认添加PDF的文档类型,得手动补上:
- 打开Info.plist,找到
Document Types数组,添加一个新条目Name填PDFTypes数组里添加com.adobe.pdf- 可选:在
Icon Files里添加PDF的图标,让DocumentBrowser显示更直观
- 同时,在
Exported Type UTIs里也可以添加PDF的UTI(虽然不是必须,但能确保系统识别):UTTypeIdentifier填com.adobe.pdfUTTypeDescription填PDF DocumentUTTypeConformsTo数组添加public.data和public.content
3. 让DocumentBrowser识别本地Documents目录的PDF
默认情况下,DocumentBrowser可能只显示iCloud Drive的文件,要让它能看到你存在本地Documents目录的PDF:
在DocumentBrowserViewController的初始化或者viewDidLoad里,配置支持的类型和本地访问:
override func viewDidLoad() { super.viewDidLoad() delegate = self // 指定支持的文档类型为PDF supportedContentTypes = ["com.adobe.pdf"] // 配置允许创建文档、访问本地文件 let config = UIDocumentBrowserViewController.Configuration() config.allowsDocumentCreation = true config.browserUserInterfaceStyle = .automatic configuration = config }
4. 生成PDF时确保UTI正确设置
你之前生成PDF的代码要确保文件的类型标识是PDF,这样DocumentBrowser才能正确识别:
// 生成PDF到documents目录后的代码 let pdfURL = documentsDirectory.appendingPathComponent("myGeneratedPDF.pdf") // 设置文件UTI为PDF try? FileManager.default.setAttributes([.type: UTTypePDF.identifier], ofItemAtPath: pdfURL.path)
做完这些步骤后,重新运行App,应该就能在DocumentBrowser里看到你生成的PDF,点击后也能在DocumentViewController里正常显示了。如果还是有问题,可以检查下Documents目录里的PDF是否真的存在,用Xcode的Window > Devices and Simulators里的Download Container来查看文件。
内容的提问来源于stack exchange,提问作者fario

