RyanTCB
RyanTCB

Reputation: 8224

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!)
                    }
              }

            }

        }

Upvotes: 7

Views: 1307

Answers (1)

RyanTCB
RyanTCB

Reputation: 8224

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)! 
}

Upvotes: 5

Related Questions