swiftpdfview

Swift 4: Change / Clear PDFView content


I want to use PDFView framework in Swift 4. (https://developer.apple.com/documentation/pdfkit/pdfview)

The following function receives a path to a PDF document. If the path is valid, the PDF file is successful shown. A problem occurs, when I call openMe(path: String) twice. In this case, the old content is still there and the new content is added. I just want to change the old content with the new content.

private var pdfData: NSData? = nil

func openMe(path: String) {
   let fileManager = FileManager.default

   if fileManager.fileExists(atPath: path){
       let url = NSURL.fileURL(withPath: path)
       pdfData = NSData(contentsOfFile: path)
       let pdfView = PDFView(frame: self.view.frame)
       pdfViewController?.pdfViewControllerInformsMeasurementDataViewController = self
       pdfView.document = PDFDocument(url: url)
       pdfView.autoScales = true
       pdfView.maxScaleFactor = 0.5
       pdfView.minScaleFactor = pdfView.scaleFactorForSizeToFit
       pdfView.autoresizingMask = [.flexibleWidth, .flexibleHeight]

       self.pdfViewController?.view.addSubview(pdfView)
       self.show(self.pdfViewController!, sender: nil)
    }
}

EDIT

Refer to excitedmicrobe's answer: I just changed the code like shown in the answer but the distance between the navigation controller and the PDFView differs.

Fist openMe call:

enter image description here

Second openMe call:

enter image description here


Solution

  • In that case, you would need to make your pdfView global:

    Before viewDidLoad() add the following:

    var pdfView = PDFView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        // ....
    }
    

    And edit your code openMe() to:

    func openMe(path: String) {
         if self.pdfViewController?.view.subviews.contains(pdfView) {
              self.pdfView.removeFromSuperview() // Remove it
          } else {
              // Do Nothing
          }
    
         let fileManager = FileManager.default
    
       if fileManager.fileExists(atPath: path){
           let url = NSURL.fileURL(withPath: path)
           pdfData = NSData(contentsOfFile: path)
           self.pdfView = PDFView(frame: self.view.frame)
           pdfViewController?.pdfViewControllerInformsMeasurementDataViewController = self
           pdfView.document = PDFDocument(url: url)
           pdfView.autoScales = true
           pdfView.maxScaleFactor = 0.5
           pdfView.minScaleFactor = pdfView.scaleFactorForSizeToFit
           pdfView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
    
           self.pdfViewController?.view.addSubview(pdfView)
           self.show(self.pdfViewController!, sender: nil)
         }
    }