Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PDFKit memory issues ios12

Edited this question to use a simpler version of the code. The TestPDF is all text and about 300 pages. As the loop runs it crashes after consuming 2gb of memory. I don’t need the value in the print statement after it’s printed. However the code keeps it in memory. How to clear the memory allocation of the contents of the print statement before the loop closes?

func loadPDFDocument(){
        let documentURL = Bundle.main.url(forResource: "TestPDF", withExtension: "pdf")!

        if let document = PDFDocument(url: documentURL) {

            for page in 1...document.pageCount {
                DispatchQueue.global().async {
                print(document.page(at: page)!.string!)
                }
            }

        }

    }

Solutions I have tried include autoreleasepool and creating a new PDFDocument object in for each loop and using that. That second option does free the memory but is seriously too slow.

 func loadPDFDocument(){
        let documentURL   = Bundle.main.url(forResource: "TestPDF", withExtension: "pdf")!

     if let document      = PDFDocument(url: documentURL) {



            for page in 1...document.pageCount {
                 DispatchQueue.global().async {
                  let innerDocument = PDFDocument(url: documentURL)!
                     print(innerDocument.page(at: page)!.string!)
                    }
              }

            }

        }
like image 873
RyanTCB Avatar asked Feb 23 '18 23:02

RyanTCB


1 Answers

my solution so far has been to reload the PDFDocument in didReceiveMemoryWarning

so I have a global variable

 var document =  PDFDocument()

use it

let pdfURL   = ...
     document =   PDFDocument(url: pdfURL)! 

then if low memory

 override func didReceiveMemoryWarning() {
    let pdfURL   = ...
        document =  PDFDocument(url: pdfURL)! 
}
like image 183
RyanTCB Avatar answered Nov 17 '22 17:11

RyanTCB