我已经从网络服务下载了一个 pdf 文件。我在设备容器中找到了它。我的文件位置如下
file:///var/mobile/Containers/Data/Application/1E4AFEDC-E3A6-4E33-9021-217A61567597/Documents/myfile.pdf
但是当我想从上面的位置打开文件时没有任何反应。这是我的代码..
let pdfView = PDFView()
pdfView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(pdfView)
pdfView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor).isActive = true
pdfView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor).isActive = true
pdfView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
pdfView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true
guard let path = Bundle.main.url(forResource: "file:///var/mobile/Containers/Data/Application/8180A938-D770-48AE-9FC7-ADE939B1D9FA/Documents/myfile", withExtension: "pdf") else { return }
if let document = PDFDocument(url: path) {
pdfView.document = document
}
请帮助和建议我..
最佳答案
问题是您尝试访问的文件显然不属于应用程序 bundle ,因为 bundle 是只读的,因此从互联网下载的文件不会存储在 bundle 中。此外,您为 Bundle.main.url(forResource:)
提供了一个完整的文件路径,而该函数只需要一个到捆绑文件的本地路径。
您需要使用 URL(fileURLWithPath:)
而不是 Bundle.url(forResource:)
。
let pdfUrl = URL(fileURLWithPath: "file:///var/mobile/Containers/Data/Application/8180A938-D770-48AE-9FC7-ADE939B1D9FA/Documents/myfile.pdf")
if let document = PDFDocument(url: path) {
pdfView.document = document
}
关于ios - 如何在 swift 4 中从设备容器中的文档文件夹中打开 pdf 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50927089/