ios - 如何在 swift 4 中从设备容器中的文档文件夹中打开 pdf 文件

标签 ios swift pdf

我已经从网络服务下载了一个 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/

相关文章:

swift - 对任意值的字典数组进行排序

java - PDFBox 输出问号而不是一些日语字符

ios - 如何使用自动布局用多个 UILabel 填充 UITableViewCell

ios - 在 Swift 中每天刷新一次应用程序的 JSON 内容

iOS 动态 UI 简单来说?

cocoa-touch - iPad 上 PDF 的替代方案

objective-c - iOS 上的 HTML 到 PDF 转换?

iphone - 用于 iphone/ipad 选择的标签栏自定义图像

ios - 为 Xcode Pods 文件夹添加 Git Ignore 不起作用

swift - 为什么要在函数中使用参数?