Swift PDFDocument对于文件和URL返回零

时间:2019-01-10 15:18:43

标签: ios swift pdf fatal-error ios-pdfkit

我想在iOS应用中使用PDFView显示PDF文件。我已经在项目目录中添加了一个名为merlin.pdf的文件。我还检查了merlin.pdf是否包含在构建阶段的副本捆绑资源中。但是,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.
    }
}

我该怎么办?

2 个答案:

答案 0 :(得分:1)

也许您错过了在界面构建器中为pdfView出口设置视图的类吗?enter image description here

因为您的代码很好,并且对我有用。

答案 1 :(得分:1)

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

相关问题