iosswiftpdfkitpdfview

iOS: How to clear PDFView?


I am showing some PDF files with PDFView class. There is a problem which is when I load or better to say replace another file, the last loaded file still visible when the new file is loaded.

enter image description here

Here is the code:

var pdfView = PDFView()
//MARK: - PDF KIT
func previewPDF(url:URL) {
    
    if self.view.subviews.contains(pdfView) {
         self.pdfView.removeFromSuperview() // Remove it
     } else {
        
     }
    
    pdfView = PDFView(frame: PDFPreview.bounds)
    pdfView.removeFromSuperview()
    
    pdfView.backgroundColor = .clear
    pdfView.displayMode = .singlePage
    pdfView.autoScales = true
    pdfView.pageShadowsEnabled = false
    pdfView.document = PDFDocument(url: url)
    
    thumbnail = PDFThumbnail(url: url, width: 240)
    
    // I tried to nil PDFPreview, still nothing happened
    PDFPreview.addSubview(pdfView)
}

Solution

  • Here you are adding pdfView as a subview of PDFPreview but on the first attempt of removing it, you are checking whether it is present in the subview of self.view but actually its in the subview of PDFPreview. So change it to the following code

    func previewPDF(url:URL) {
        if PDFPreview.subviews.contains(pdfView) {
           self.pdfView.removeFromSuperview() // Remove it
         } else { 
       
       }
    

    And also when u try to remove it the second time using removeFromSuperview() you have already instantiated another PDFView() and lost the reference to the old one and hence the removal of old PDFView fails at that point too.

    Alternate Solution: If you are just changing the pdf document a better solution is just to change the document property of the PDFView. eg:

    if let document = PDFDocument(url: path) {
        pdfView.document = document
      }