0

I want to show a PDF file using PDFView in an iOS app. I have added a file called merlin.pdf to my project directory. I have also checked that merlin.pdf is included in the Copy Bundle Resources in Build Phases. But still, PDFDocument returns nil. This is the code I'm using:

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.
    }
}

The fatal error is thrown at pdfView.document = pdfDocument.

Then, I tried an online link to the PDF file. While debugging, I can see that let pdfDocument = PDFDocument(url: url!) is donwloading the file from the internet. But again, it fails just like last time. This is the code:

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.
    }
}

What should I do?

Vicarious
  • 131
  • 18

2 Answers2

2

Maybe you missed to set the class of the view in the interface builder for your pdfView outlet?enter image description here

Because your code is fine and works for me.

Klinki
  • 368
  • 1
  • 11
2

Well strangely enough, the problem was with the weak keyword in @IBOutlet weak var pdfView: PDFView!. Removing the weak made the code work. Thanks to @klinki for mentioning the outlet.

Vicarious
  • 131
  • 18