Can I schedule multiple print jobs in parallel using UIPrintInteractionController?

49 views Asked by At

For printing from worker thread to a UIPrinter (whose URL I have saved), I am doing this and able to print:

func PrintPdfDocument (pDocument:Data)
{
    // Create a print interaction controller
    let printController = UIPrintInteractionController.shared
    
    // Set the printing options
    let printInfo = UIPrintInfo(dictionary:nil)
    printInfo.jobName = "Print Job "
    printController.printInfo = printInfo
    printController.showsPageRange = true
    
    // Set the PDF document to be printed
    printController.printingItems = pDocument
    
    printController.print(to: defaulttprinter, completionHandler: { (controller, completed, error) in
        if completed {
            print("Printing successful!")
        } else {
            if let error = error {
                print("Printing failed with error: \(error.localizedDescription)")
            } else {
                print("Printing was canceled.")
            }
        }
    })
}

When I call the PrintPdfDocument(pDocument:Data) function more than once with different data shown below:

DispatchQueue.global().async {
    PrintPdfDocument (pDocument:data1)
}
DispatchQueue.global().async {
    PrintPdfDocument (pDocument:data2)
}
DispatchQueue.global().async {
    PrintPdfDocument (pDocument:data3)
}

Printer is printing only one document(data1). For others (data2, data3) call is not executing printController.print (to....) function inside PrintPdfDocument.

1

There are 1 answers

0
Joakim Danielson On

UIPrintInteractionController is tagged with MainActor so there is not much point in creating and using it from a background thread.

Since UIPrintInteractionController can be passed an array of documents to print it is most likely the most efficient way to print your pdf files since the printer itself will only handle one job at a time and since it's a shared object it seems to simply ignore and extra job added while it is printing.

func PrintPdfDocument(pDocuments: [Data]) {
    let printController = UIPrintInteractionController.shared

    let printInfo = UIPrintInfo(dictionary:nil)
    printInfo.jobName = "Print Job "
    printController.printInfo = printInfo
    
    printController.printingItems = pDocuments // Add all jobs here
    
    printController.print(to: UIPrinter(url: defaultPrinter), completionHandler: { (controller, completed, error) in
        if completed {
            print("Printing successful!")
        } else {
            if let error = error {
                print("Printing failed with error: \(error.localizedDescription)")
            } else {
                print("Printing was canceled.")
            }
        }
    })        
}

And instead call it with an array of documents

PrintPdfDocument(pDocuments: [data1, data2, data3])