【问题标题】:How to open pdf file from Documents folder in device Container in swift 4如何在swift 4中从设备容器中的文档文件夹中打开pdf文件
【发布时间】:2018-11-28 08:09:22
【问题描述】:

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

请帮助和建议我..

【问题讨论】:

  • 为什么不使用 QL Preview 控制器打开 pdf?
  • @Umar Farooque 你好先生,我只是从网络服务下载 pdf 文件并查看下载的 pdf 文件。如何使用 QL Preview 控制器
  • QL Preview 控制器可以为您提供对 pdf 的更多控制,包括在其他应用程序之间共享它的选项。 appcoda.com/quick-look-framework

标签: ios swift pdf


【解决方案1】:

问题是您正在尝试访问一个明显不属于应用程序包的文件,因为该包是只读的,因此从互联网下载的文件不会存储在包中。此外,您提供了一个完整的文件路径到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
}

【讨论】:

  • 嘿@David Pasztor,我不知道我在哪里做错了,但它不起作用。我按照您的修改逐行跟踪代码。
【解决方案2】:

你需要用这个来获取文档路径:

let fileManager = NSFileManager.defaultManager()

let urls = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)

if let documentDirectory: NSURL = urls.first as? NSURL {
    // This is where the database should be in the documents directory
    let finalFileURL = documentDirectory.URLByAppendingPathComponent("myfile.pdf")

    if finalFileURL.checkResourceIsReachableAndReturnError(nil) {
        // The file already exists, so just return the URL
        return finalFileURL
    }
} else {
    println("Couldn't get documents directory!")
}

【讨论】:

  • 当旧的 Foundation 类型(NSFileManagerNSURL)有原生 Swift 替代品时,不要使用它们。
【解决方案3】:

在 Swift 5 中使用 PDFKit 处理此代码

var pdfURL = (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)).last! as URL
pdfURL = pdfURL.appendingPathComponent("myfile.pdf") as URL
pdfView.document = PDFDocument(url: pdfURL )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-17
    • 1970-01-01
    • 1970-01-01
    • 2015-11-09
    • 1970-01-01
    • 2018-05-26
    • 1970-01-01
    • 2013-12-06
    相关资源
    最近更新 更多