Search code examples
iosswiftpdfkit

Issue loading PDF for UIActivityViewController with .dataRepresentation()


I have what I thought was a simple View Controller to displayed a preloaded PDF file. The path to the PDF is passed into var pdfPath by the pervious controller.

I have an action/share button I'm trying to use for sharing and printing the PDF using PDFDocument.dataRepresentation(). According to multiple sources online, it should work, but I'm getting a strange error:

[Unknown process name] Failed to load /System/Library/PrivateFrameworks/CorePDF.framework/Versions/A/CorePDF

Code:

import UIKit
import PDFKit

class PDFViewController: UIViewController {

@IBOutlet weak var ActionBarButton: UIBarButtonItem!

var pdfPath: String? = nil

override func viewDidLoad() {
    super.viewDidLoad()
    let pdfView = PDFView(frame: self.view.bounds)
    self.view.addSubview(pdfView)
    pdfView.autoScales = true
    
    if let path = pdfPath {
        let fileURL = Bundle.main.url(forResource: path, withExtension: "pdf")
         pdfView.document = PDFDocument(url: fileURL!)!
    }
}

@IBAction func ActionButtonPressed(_ sender: UIBarButtonItem) {
    print("ActionButtonPressed():")
    
    if let path = pdfPath {
        let fileURL = Bundle.main.url(forResource: path, withExtension: "pdf")
        let pdfDocument = PDFDocument(url: fileURL!)
        
        guard let data = pdfDocument?.dataRepresentation() else {return}
        let activityController = UIActivityViewController(activityItems: [data], applicationActivities: nil)
        self.present(activityController, animated: true, completion: nil)
    }
}

If anyone knows the answer to why this isn't working I'd be very grateful.


Solution

  • Rather than passing the data, you can pass the URL of the file, which UIActivityViewController will recognise and display share options accordingly.

    let activityController = UIActivityViewController(activityItems: [fileURL], applicationActivities: nil)