skip to Main Content

The code bellow works on iPad but not on macOS using "designed for iPad" mode. I get this error.

CGContextClipToRect: invalid context 0x0. If you want to see the backtrace, please set CG_CONTEXT_SHOW_BACKTRACE environmental variable.

How can I modify the code to runs correctly on macOS?

import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack {
            Button("print"){
                prt()
            }
        }
        .padding()
    }
    
    func prt(){
        let htmlString = "<h1>Hello World</h1>"
        let formatter: UIMarkupTextPrintFormatter = UIMarkupTextPrintFormatter(markupText: htmlString)
        let printInfo = UIPrintInfo(dictionary: nil)
        printInfo.jobName = "test"
        printInfo.outputType = .general
        let printController = UIPrintInteractionController.shared
        printController.printInfo = printInfo
        printController.showsNumberOfCopies = true
        printController.printFormatter = formatter
        let controller = UIViewController()
        DispatchQueue.main.async {
            printController.present(animated: true, completionHandler: { _, _, _ in
                printController.printFormatter = nil
            })
        }
    }
}

2

Answers


  1. Chosen as BEST ANSWER

    I find a temporary solution solution for my issue using WKWebView.

    import SwiftUI
    import WebKit
    
    struct ContentView: View {
        @State private var showPicker = false
        var body: some View {
            VStack {
                Button("print"){
                      prt()
                }
            }
            .padding()
        }
        
        func prt(){
            let htmlString = "<h1>Hello World</h1>"
            if (isiOSAppOnMac()){
               _ = WebPrintPageRendererAndPrint(htmlString: htmlString)
            }else{
                printiOS()
            }
        }
        
        func printiOS(){
            let htmlString = "<h1>Hello World</h1>"
                let formatter: UIMarkupTextPrintFormatter = UIMarkupTextPrintFormatter(markupText: htmlString)
                let printInfo = UIPrintInfo(dictionary: nil)
                printInfo.jobName = "test"
                printInfo.outputType = .general
                let printController = UIPrintInteractionController.shared
                printController.printInfo = printInfo
                printController.showsNumberOfCopies = true
                printController.printFormatter = formatter
                    printController.present(animated: true, completionHandler: { _, _, _ in
                        printController.printFormatter = nil
                    })
                }
        }
        
    func isiOSAppOnMac() -> Bool {
      if #available(iOS 14.0, *) {
        return ProcessInfo.processInfo.isiOSAppOnMac
      }
      return false
    }
    

    WebPrintPageRenderer.swift file

    import Foundation
    import UIKit
    import WebKit
    
    class WebPrintPageRendererAndPrint: UIPrintPageRenderer,WKNavigationDelegate {
        let htmlString: String
        let wb = WKWebView(frame: CGRect(x: 0, y: 0, width: 300, height: 300))
    
    
        init(htmlString: String) {
            self.htmlString = htmlString
            super.init()
            wb.loadHTMLString(htmlString, baseURL: nil)
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                let printFormatter = self.wb.viewPrintFormatter()
                self.addPrintFormatter(printFormatter, startingAtPageAt: 0)
                let info = UIPrintInfo.printInfo()
                info.outputType = .general
                info.orientation = .portrait
                info.jobName = "test"
                
                let printInteractionController = UIPrintInteractionController.shared
    
                printInteractionController.printPageRenderer = self
                printInteractionController.printInfo = info
                printInteractionController.present(animated: true)
             
            }
        }       
    }
    

  2. I don’t have a solution, but I also encountered this problem yesterday (what are the odds?). I just filed the following feedback report and would encourage others encountering this issues to also file a report:

    FB13420491: Print command hangs when running a "Designed for iPad" App
    on macOS: CGContextClipToRect: invalid context 0x0

    My app is written in Obj-C and the code is similar to what you have above (at least in my case, I don’t think the dispatch_async is necessary, since the action is already invoked on the main queue):

    - (IBAction)print:(id)sender {
        UISimpleTextPrintFormatter * printFormatter = [[UISimpleTextPrintFormatter alloc] initWithText:@"TEXT"];
        if ( printFormatter ) {
            UIPrintInfo * printInfo = UIPrintInfo.printInfo;
            printInfo.outputType = UIPrintInfoOutputGrayscale;
    
            printFormatter.color = nil; // FB13418343 default is labelColor (i.e. white in Dark Mode)
    
            UIPrintInteractionController * printController = UIPrintInteractionController.sharedPrintController;
            printController.printInfo = printInfo;
            printController.printFormatter = printFormatter;
            [printController presentAnimated:YES completionHandler:^(UIPrintInteractionController * _Nonnull printInteractionController, BOOL completed, NSError * _Nullable error) {
                NSLog(@"print completed: %u %@", completed, error);
            }];
        }
    }
    

    The completion is never invoked (unless I hit Command-P twice):

    With CG_CONTEXT_SHOW_BACKTRACE=YES I get this:

    CGContextClipToRect: invalid context 0x0. Backtrace:
      <RemotePDEServiceInterface+13092>
       <RemotePDEServiceInterface+11960>
        <RemotePDEServiceInterface+10308>
         <main+9188>
          <-[_NSCollectionViewCore _computePrefetchCandidatesForVisibleBounds:futureVisibleBounds:prefetchVector:notifyDelegateIfNe
           <-[_NSCollectionViewCore _computePrefetchCandidatesForRect:]+232>
            <-[_NSCollectionViewCore _layoutItems]+172>
             <-[NSCollectionView layout]+304>
              <___NSViewLayout_block_invoke+592>
               <NSPerformVisuallyAtomicChange+108>
                <_NSViewLayout+96>
                 <__36-[NSView _layoutSubtreeWithOldSize:]_block_invoke+364>
                  <NSPerformVisuallyAtomicChange+108>
                   <-[NSView _layoutSubtreeWithOldSize:]+100>
                    <__36-[NSView _layoutSubtreeWithOldSize:]_block_invoke+688>
                     <NSPerformVisuallyAtomicChange+108>
                      <-[NSView _layoutSubtreeWithOldSize:]+100>
                       <__36-[NSView _layoutSubtreeWithOldSize:]_block_invoke+688>
                        <NSPerformVisuallyAtomicChange+108>
                         <-[NSView _layoutSubtreeWithOldSize:]+100>
                          <__36-[NSView _layoutSubtreeWithOldSize:]_block_invoke+688>
                           <NSPerformVisuallyAtomicChange+108>
                            <-[NSView _layoutSubtreeWithOldSize:]+100>
                             <__36-[NSView _layoutSubtreeWithOldSize:]_block_invoke+688>
                              <NSPerformVisuallyAtomicChange+108>
                               <-[NSView _layoutSubtreeWithOldSize:]+100>
                                <__36-[NSView _layoutSubtreeWithOldSize:]_block_invoke+688>
                                 <NSPerformVisuallyAtomicChange+108>
                                  <-[NSView _layoutSubtreeWithOldSize:]+100>
                                   <__36-[NSView _layoutSubtreeWithOldSize:]_block_invoke+688>
                                    <NSPerformVisuallyAtomicChange+108>
                                     <-[NSView _layoutSubtreeWithOldSize:]+100>
                                      <__56-[NSView _layoutSubtreeIfNeededAndAllowTemporaryEngine:]_block_invoke+796>
                                       <NSPerformVisuallyAtomicChange+108>
                                        <-[NSView _layoutSubtreeIfNeededAndAllowTemporaryEngine:]+100>
                                         <NSPerformVisuallyAtomicChange+108>
                                          <-[NSView layoutSubtreeIfNeeded]+96>
                                           <-[NSWindow(NSConstraintBasedLayoutInternal) _layoutViewTree]+104>
                                            <-[NSWindow(NSConstraintBasedLayoutInternal) layoutIfNeeded]+240>
                                             <__NSWindowGetDisplayCycleObserverForLayout_block_invoke+364>
                                              <NSDisplayCycleObserverInvoke+168>
                                               <NSDisplayCycleFlush+644>
                                                <__37+[NSDisplayCycle currentDisplayCycle]_block_invoke.7+28>
                                                 <___NSMainRunLoopPerformBlockInModes_block_invoke+44>
                                                  <__CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__+28>
                                                   <__CFRunLoopDoBlocks+356>
                                                   <__CFRunLoopRun+812>
                                                   <CFRunLoopRunSpecific+608>
                                                   <-[NSRunLoop(NSRunLoop) runMode:beforeDate:]+212>
                                                   <-[NSRunLoop(NSRunLoop) runUntilDate:]+100>
                                                   <-[UINSPDFPrintingView _generatePDF]+324>
                                                   <-[UINSPDFPrintingView pdfDocument]+72>
                                                   <-[UINSPDFPrintingView knowsPageRange:]+72>
                                                   <-[NSView(NSPrinting2) _knowsPagesFirst:last:]+176>
                                                   <__59-[NSConcretePrintOperation(NSInternal) _validatePagination]_block_invoke+21
                                                   <NSPerformVisuallyAtomicChange+108>
                                                   <-[NSConcretePrintOperation(NSInternal) _validatePagination]+124>
                                                   <-[NSConcretePrintOperation(NSInternal) _firstPageNumber]+24>
                                                   <-[NSConcretePrintOperation pageRange]+24>
                                                   <__67-[NSPrintPanel _makePrintWindowControllerWithPrintOperation:sheet:]_block_i
                                                   <PMAppendToSummaryString+96940>
                                                   <__CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__+148>
                                                   <___CFXRegistrationPost_block_invoke+88>
                                                   <_CFXRegistrationPost+440>
                                                   <_CFXNotificationPost+764>
                                                   <-[NSNotificationCenter postNotificationName:object:userInfo:]+88>
                                                   <PMPrintPanelSetAppThumbnailViewPrivate+3460>
                                                   <-[NSObject(NSKeyValueObservingPrivate) _changeValueForKeys:count:maybeOldValues
                                                   <-[NSObject(NSKeyValueObservingPrivate) _changeValueForKey:key:key:usingBlock:]+
                                                   <_NSSetObjectValueAndNotify+284>
                                                   <main+56728>
                                                   <__NSDICTIONARY_IS_CALLING_OUT_TO_A_BLOCK__+24>
                                                   <-[__NSDictionaryM enumerateKeysAndObjectsWithOptions:usingBlock:]+288>
                                                   <main+53188>
                                                   <main+161412>
                                                   <main+148520>
                                                   <PMPrintPanelSetAppThumbnailViewPrivate+32920>
                                                   <PMAppendToSummaryString+93600>
                                                   <-[NSWindowController _windowDidLoad]+620>
                                                   <-[NSWindowController window]+84>
                                                   <-[NSPrintPanel beginSheetUsingPrintInfo:onWindow:completionHandler:]+440>
                                                   <__91-[NSConcretePrintOperation runOperationModalForWindow:delegate:didRunSelect
                                                   <-[NSConcretePrintOperation runOperationModalForWindow:delegate:didRunSelector:c
                                                   <__65-[UINSPrintingController _runModalPrintOperation:withCompletion:]_block_inv
                                                   <__CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__+28>
                                                   <__CFRunLoopDoBlocks+356>
                                                   <__CFRunLoopRun+812>
                                                   <CFRunLoopRunSpecific+608>
                                                   <RunCurrentEventLoopInMode+292>
                                                   <ReceiveNextEventCommon+220>
                                                   <_BlockUntilNextEventMatchingListInModeWithFilter+76>
                                                   <_DPSNextEvent+660>
                                                   <-[NSApplication(NSEventRouting) _nextEventMatchingEventMask:untilDate:inMode:de
                                                   <-[NSApplication run]+476>
                                                   <NSApplicationMain+880>
                                                   <+[NSWindow _savedFrameFromString:]+0>
                                                   <UINSApplicationMain+972>
                                                   <UIApplicationMain+148>
                                                   <main+204>                                               <start+2360>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search