0

我想在 iOS 应用程序中使用 PDFView 显示 PDF 文件。我在我的项目目录中添加了一个名为 merlin.pdf 的文件。我还检查了 merlin.pdf 是否包含在 Build Phases 的 Copy Bundle Resources 中。但是,PDFDocument 仍然返回 nil。这是我正在使用的代码:

import UIKit
import PDFKit

class ReaderViewController: UIViewController {

    // MARK: - Properties
    @IBOutlet weak var pdfView: PDFView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let url = Bundle.main.url(forResource: "merlin", withExtension: "pdf")
        let pdfDocument = PDFDocument(url: url!)

        pdfView.document = pdfDocument
        pdfView.displayMode = PDFDisplayMode.singlePageContinuous
        pdfView.autoScales = true


        // Do any additional setup after loading the view.
    }
}

致命错误在pdfView.document = pdfDocument.

然后,我尝试了 PDF 文件的在线链接。在调试时,我可以看到let pdfDocument = PDFDocument(url: url!)正在从 Internet 下载文件。但是,它又像上次一样失败了。这是代码:

import UIKit
import PDFKit

class ReaderViewController: UIViewController {

    // MARK: - Properties
    @IBOutlet weak var pdfView: PDFView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let url = URL(string: "https://arxiv.org/pdf/1803.10760.pdf")
        let pdfDocument = PDFDocument(url: url!)

        pdfView.document = pdfDocument
        pdfView.displayMode = PDFDisplayMode.singlePageContinuous
        pdfView.autoScales = true


        // Do any additional setup after loading the view.
    }
}

我应该怎么办?

4

2 回答 2

2

也许您错过了在界面构建器中为您的 pdfView 插座设置视图的类?在此处输入图像描述

因为你的代码很好,对我有用。

于 2019-01-10T15:45:02.047 回答
2

奇怪的是,问题出在weak关键字 in 上@IBOutlet weak var pdfView: PDFView!。删除weak使代码工作。感谢@klinki 提到了出口。

于 2019-01-10T16:11:59.360 回答