【问题标题】:Swift PDFDocument return nil for files and urlsSwift PDFDocument 为文件和 url 返回 nil
【发布时间】:2019-01-10 15:18:42
【问题描述】:

我想在 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.
    }
}

我该怎么办?

【问题讨论】:

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


    【解决方案1】:

    也许您错过了在界面构建器中为您的 pdfView 插座设置视图的类?

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2018-01-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-04-26
        • 2017-08-15
        相关资源
        最近更新 更多