Search code examples
swiftpdfkit

How to optimize the code after write a file successfully


Create Pdf

I am Working on create a pdf multiple image unlimited images but the main issue is pdfKit after write not release the memory then the issue is app crashed after 1 GB Exceed Can anyone to help me to image to pdf Unlimited Images. i have using recursive function to release memory but in my case memory not relase i have shared the code kidly help

 func createPdfRecursiveFunction(image:UIImage,imageData:[UIImage],name:String)
    {
        
        autoreleasepool(invoking: {
            let pdfPage = PDFPage(image: image)!
        pdfdocument.insert(pdfPage, at: ImagesCount)
        if ImagesCount == (imageData.count - 1)
        {
            print("Write Successfully")
        }else{
            ImagesCount += 1
            if ImagesCount == (imageData.count - 1)
            {
                self.getAllImage.removeAll()
                self.imagedata.removeAll()
                print("Write Successfully")
                let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
                var outputURL = documentDirectory.appendingPathComponent("PDFReader")
                do {
                    try FileManager.default.createDirectory(at: outputURL, withIntermediateDirectories: true, attributes: nil)
                    outputURL = outputURL.appendingPathComponent("\(name).pdf")
                }catch let error {
                    print(error.localizedDescription)
                }
                _ = autoreleasepool
                   {
                pdfdocument.write(to: outputURL)
                   }
               
            }else{
                createPdfRecursiveFunction(image: imagedata[ImagesCount], imageData: imageData, name: name)
            }
        }})
    }

Solution

  • The issue is you are recursively calling the createPdfRecursiveFunction from within the autorelease block itself, which means the block wont reach the end and drain until all images have been processed.

    Either call the createPdfRecursiveFunction just after the end of the autorelease block, or separate your code so that the pdf work is done in a separate function with an autorelease block e.g.

    createPdfRecursiveFunction() {
       if imageToBeWritten {addImageToPDF(image)}
    }
    
    addImageToPDF(image:UIImage) {
        @autoreleasepool {
          // Add image to pdf code here
        }
    }