Crash when presenting UIPrintInteractionController on iOS 16

Starting iOS 16 seeing some crashes related to pdf printing in the crash reporter. It looks like the issue is not so frequent. Also, I'm unable to reproduce the crash. Looks like the app crashes when the print preview dialog is opening. According to crash reports, there are some crashes on different iOS 16 versions: 16.0.0, 16.0.2, and 16.0.3.

Printing code:

let printInfo = UIPrintInfo.printInfo()
printInfo.jobName = "Printing Job Name"
self.printViewController = UIPrintInteractionController.shared
self.printViewController?.printInfo = printInfo
self.printViewController?.printingItem = pdfURL
self.printViewController?.present(from: barButtonItem, animated: true) { (controller, completed, error) in
      self.printViewController = nil
}

Stack trace:

compare_key + 4 (CGPDFObject.c:134)
bsearch + 68 (bsearch.c:70)
CGPDFDictionaryGetUnresolvedObject + 68 (CGPDFDictionary.c:153)
CGPDFDictionaryGetObject + 44 (CGPDFDictionary.c:172)
CGPDFDictionaryGetDictionary + 44 (CGPDFDictionary.c:284)
get_pages_dictionary + 68 (pdf-reader.c:410)
pdf_reader_get_number_of_pages + 76 (pdf-reader.c:557)
-[UIPrintPreviewPageFetcher fetchNumberOfItems] + 76 (UIPrintPreviewPageFetcher.m:115)
-[UIPrintPreviewViewController collectionView:numberOfItemsInSection:] + 32 (UIPrintPreviewViewController.m:482)
-[UICollectionViewData _updateItemCounts] + 220 (UICollectionViewData.mm:335)
-[UICollectionViewData isIndexPathValid:validateItemCounts:] + 52 (UICollectionViewData.mm:348)
-[UICollectionViewData validatedGlobalIndexForItemAtIndexPath:] + 36 (UICollectionViewData.mm:778)
-[UICollectionView _cellForItemAtIndexPath:] + 108 (UICollectionView.m:7112)
-[UICollectionView _endItemAnimationsWithInvalidationContext:tentativelyForReordering:animator:collectionViewAnimator:] + 1384 (UICollectionView.m:9357)
-[UICollectionView _updateRowsAtIndexPaths:updateAction:updates:] + 396 (UICollectionView.m:9104)
-[UICollectionView reloadItemsAtIndexPaths:] + 52 (UICollectionView.m:9124)
-[UIPrintPreviewViewController reloadVisibleItems:] + 256 (UIPrintPreviewViewController.m:568)
__63-[UIPrintPreviewViewController updatePdfURL:options:completed:]_block_invoke_2 + 44 (UIPrintPreviewViewController.m:305)
__NSBLOCKOPERATION_IS_CALLING_OUT_TO_A_BLOCK__ + 24 (NSOperation.m:1545)
-[NSBlockOperation main] + 104 (NSOperation.m:1564)
__NSOPERATION_IS_INVOKING_MAIN__ + 16 (NSOperation.m:2189)
-[NSOperation start] + 708 (NSOperation.m:2206)

Thanks!

Answered by webd in 762612022

I found out the cause and solved it. The problem is that when the print window is displayed, the result rendered by the UIPrintPageRenderer is previewed in real time. At this point, something crashes as rendering and previewing happen simultaneously. This is considered an API bug. The way to avoid it is not to render in real time in the print window, but to open the print window after setting the pre-rendered PDF file to printingItem before opening the print window. I didn't get any app crashes when I did this.

UIPrintInteractionController *controller = (UIPrintInteractionController*)m_pController;
CGSize pageSize = CGSizeMake(595.2, 841.8); // default A4
UIEdgeInsets pageMargins = UIEdgeInsetsMake(72, 72, 72,72);
CGRect printableRect = CGRectMake(pageMargins.left, pageMargins.top,
                                  pageSize.width - pageMargins.left - pageMargins.right,
                                  pageSize.height - pageMargins.top - pageMargins.bottom);

CGRect paperRect = CGRectMake(0, 0, pageSize.width, pageSize.height);

NSMutableData *pdfData = [NSMutableData data];
UIGraphicsBeginPDFContextToData( pdfData, paperRect, nil );
[self prepareForDrawingPages: NSMakeRange(0, self.numberOfPages)];
CGRect bounds = UIGraphicsGetPDFContextBounds();
for ( int i = 0 ; i < [self numberOfPages] ; i++ ) {
    UIGraphicsBeginPDFPage();        
    [self drawPageAtIndex: i inRect: bounds];
}
UIGraphicsEndPDFContext();

controller.printingItem = pdfdata;

We also have related crashes with UIPrintPreviewPageFetcher

Exception Type:  SIGSEGV
Exception Codes: SEGV_MAPERR at 0x8
Crashed Thread:  0

Thread 0 Crashed:
0   CoreGraphics                         0x000000018ae88ab0 CGContextDrawPDFPageWithDrawingCallbacks + 208
1   CoreGraphics                         0x000000018ae1ea00 CGContextDrawPDFPage + 32
2   PrintKitUI                           0x00000001d110fa50 getPageImageForPage + 1676
3   PrintKitUI                           0x00000001d1131b30 -[UIPrintPreviewPageFetcher _drawPageContextIntoImage:] + 292
4   PrintKitUI                           0x00000001d11313b4 -[UIPrintPreviewPageFetcher sheetImageForItemAt:] + 108
5   PrintKitUI                           0x00000001d110219c -[UIPrintPreviewViewController collectionView:cellForItemAtIndexPath:] + 128
6   UIKitCore                            0x000000018b51874c -[UICollectionView _createPreparedCellForItemAtIndexPath:withLayoutAttributes:applyAttributes:isFocused:notify:] + 952
7   UIKitCore                            0x000000018b55de8c -[UICollectionView _preparedCellForItemAtIndexPath:withLayoutAttributes:applyAttributes:isFocused:notify:] + 180
8   UIKitCore                            0x000000018bad07e4 __114-[UICollectionView _createAndAppendViewAnimationsForInsertsInCurrentUpdate:appearingAnimations:newSubviewManager:]_block_invoke + 348
9   UIKitCore                            0x000000018bad05bc -[UICollectionView _createAndAppendViewAnimationsForInsertsInCurrentUpdate:appearingAnimations:newSubviewManager:] + 1408
10  UIKitCore                            0x000000018b58d9ec -[UICollectionView _viewAnimationsForCurrentUpdateWithCollectionViewAnimator:] + 256
11  UIKitCore                            0x000000018bad4640 __102-[UICollectionView _updateWithItems:tentativelyForReordering:propertyAnimator:collectionViewAnimator:]_block_invoke.748 + 264
12  UIKitCore                            0x000000018b3fca3c +[UIView(Animation) performWithoutAnimation:] + 72
13  UIKitCore                            0x000000018b6de954 -[UICollectionView _updateWithItems:tentativelyForReordering:propertyAnimator:collectionViewAnimator:] + 1384
14  UIKitCore                            0x000000018b6ddf70 -[UICollectionView _endItemAnimationsWithInvalidationContext:tentativelyForReordering:animator:collectionViewAnimator:] + 9016
15  UIKitCore                            0x000000018b63cb54 -[UICollectionView _updateRowsAtIndexPaths:updateAction:updates:] + 392
16  UIKitCore                            0x000000018b63ded0 -[UICollectionView reloadItemsAtIndexPaths:] + 48
17  PrintKitUI                           0x00000001d11027b8 -[UIPrintPreviewViewController reloadVisibleItems:] + 252
18  PrintKitUI                           0x00000001d11012b0 __63-[UIPrintPreviewViewController updatePdfURL:options:completed:]_block_invoke_2 + 40
19  Foundation                           0x0000000183611060 __NSBLOCKOPERATION_IS_CALLING_OUT_TO_A_BLOCK__ + 20
20  Foundation                           0x00000001835e51b0 -[NSBlockOperation main] + 100
21  Foundation                           0x00000001835e5140 __NSOPERATION_IS_INVOKING_MAIN__ + 12
22  Foundation                           0x00000001835a64f4 -[NSOperation start] + 704
23  Foundation                           0x00000001835a6228 __NSOPERATIONQUEUE_IS_STARTING_AN_OPERATION__ + 12
24  Foundation                           0x00000001835ab940 __NSOQSchedule_f + 168
25  libdispatch.dylib                    0x0000000190828114 _dispatch_block_async_invoke2 + 144
26  libdispatch.dylib                    0x0000000190818f88 _dispatch_client_callout + 16
27  libdispatch.dylib                    0x00000001908277f4 _dispatch_main_queue_drain + 924
28  libdispatch.dylib                    0x0000000190827444 _dispatch_main_queue_callback_4CF + 40
29  CoreFoundation                       0x00000001892916c8 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 12
30  CoreFoundation                       0x000000018927302c __CFRunLoopRun + 2032
31  CoreFoundation                       0x0000000189277eb0 CFRunLoopRunSpecific + 608
32  GraphicsServices                     0x00000001c346d368 GSEventRunModal + 160
33  UIKitCore                            0x000000018b76d668 -[UIApplication _run] + 884
34  UIKitCore                            0x000000018b76d2cc UIApplicationMain + 336
35  MyAppp                               0x0000000104ef2bc4 main (main.m:28)
36  ???                                  0x00000001a7b70960 0x0 + 0

Device iPhone13,1 OS iOS 16.3.1

Hey, I came to the same crash, and got no idea about this. do you have any progress

Hi, @moonkake. I'm still unable to resolve this crash. The crash seems to be quite common based on the crash statistics for my app. Here is all the information I have regarding these crashes:

  • The crash is sporadic and I have not been able to reproduce it manually.
  • It only occurs on devices running iOS 16.*.
  • The crash can happen on both iPhones and iPads.
  • It doesn't seem to be related to low memory.

Stack traces can vary, there are the three most common ones:

  1. pdf_xref_get_trailer
Crashed: com.apple.main-thread
0  CoreGraphics                   0x619a0 pdf_xref_get_trailer + 16
1  CoreGraphics                   0x5e1f4 get_pages_dictionary + 24
2  CoreGraphics                   0x61528 pdf_reader_get_number_of_pages + 80
3  PrintKitUI                     0x562cc -[UIPrintPreviewPageFetcher fetchNumberOfItems] + 76
4  PrintKitUI                     0x27178 -[UIPrintPreviewViewController collectionView:numberOfItemsInSection:] + 32
5  UIKitCore                      0xa409c -[UICollectionViewData _updateItemCounts] + 228
6  UIKitCore                      0x459948 -[UICollectionViewData numberOfSections] + 40
7  UIKitCore                      0x61b78 -[UICollectionViewFlowLayout _getSizingInfosWithExistingSizingDictionary:] + 500
8  UIKitCore                      0x6191c -[UICollectionViewFlowLayout _fetchItemsInfoForRect:] + 248
9  UIKitCore                      0x75d80 -[UICollectionViewFlowLayout prepareLayout] + 192
10 UIKitCore                      0x74044 -[UICollectionViewData _prepareToLoadData] + 192
11 UIKitCore                      0x43d12c -[UICollectionViewData validateLayoutInRect:] + 96
12 UIKitCore                      0x28f4c -[UICollectionView layoutSubviews] + 220
13 UIKitCore                      0x4be0 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 1992
14 QuartzCore                     0xa074 CA::Layer::layout_if_needed(CA::Transaction*) + 500
15 QuartzCore                     0x1d5f0 CA::Layer::layout_and_display_if_needed(CA::Transaction*) + 148
16 QuartzCore                     0x2ea1c CA::Context::commit_transaction(CA::Transaction*, double, double*) + 444
17 QuartzCore                     0x5dff4 CA::Transaction::commit() + 648
18 QuartzCore                     0x47f3c CA::Transaction::flush_as_runloop_observer(bool) + 88
19 UIKitCore                      0x4fdc04 _UIApplicationFlushCATransaction + 52
20 UIKitCore                      0x64e4b0 _UIUpdateSequenceRun + 84
21 UIKitCore                      0xcb2c8c schedulerStepScheduledMainSection + 144
22 UIKitCore                      0xcb21e8 runloopSourceCallback + 92
23 CoreFoundation                 0xd3128 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 28
24 CoreFoundation                 0xdf7b4 __CFRunLoopDoSource0 + 176
25 CoreFoundation                 0x645e8 __CFRunLoopDoSources0 + 244
26 CoreFoundation                 0x7a0d4 __CFRunLoopRun + 828
27 CoreFoundation                 0x7f3ec CFRunLoopRunSpecific + 612
28 GraphicsServices               0x135c GSEventRunModal + 164
29 UIKitCore                      0x39d6e8 -[UIApplication _run] + 888
30 UIKitCore                      0x39d34c UIApplicationMain + 340
...
  1. pdf_reader_get_number_of_pages
Crashed: com.apple.main-thread
0  CoreGraphics                   0x69aac pdf_reader_get_number_of_pages + 28
1  PrintKitUI                     0x562b8 -[UIPrintPreviewPageFetcher fetchNumberOfItems] + 76
2  PrintKitUI                     0x27100 -[UIPrintPreviewViewController collectionView:numberOfItemsInSection:] + 32
3  UIKitCore                      0xa6be4 -[UICollectionViewData _updateItemCounts] + 220
4  UIKitCore                      0x1305c -[UICollectionViewData isIndexPathValid:validateItemCounts:] + 52
5  UIKitCore                      0x113c4 -[UICollectionViewData validatedGlobalIndexForItemAtIndexPath:] + 36
6  UIKitCore                      0x66f50 -[UICollectionView _cellForItemAtIndexPath:] + 108
7  UIKitCore                      0x31019c -[UICollectionView _endItemAnimationsWithInvalidationContext:tentativelyForReordering:animator:collectionViewAnimator:] + 1384
8  UIKitCore                      0x270b54 -[UICollectionView _updateRowsAtIndexPaths:updateAction:updates:] + 396
9  UIKitCore                      0x271ed0 -[UICollectionView reloadItemsAtIndexPaths:] + 52
10 PrintKitUI                     0x277b8 -[UIPrintPreviewViewController reloadVisibleItems:] + 256
11 PrintKitUI                     0x262b0 __63-[UIPrintPreviewViewController updatePdfURL:options:completed:]_block_invoke_2 + 44
12 Foundation                     0xa7060 __NSBLOCKOPERATION_IS_CALLING_OUT_TO_A_BLOCK__ + 24
13 Foundation                     0x7b1b0 -[NSBlockOperation main] + 104
14 Foundation                     0x7b140 __NSOPERATION_IS_INVOKING_MAIN__ + 16
15 Foundation                     0x3c4f4 -[NSOperation start] + 708
16 Foundation                     0x3c228 __NSOPERATIONQUEUE_IS_STARTING_AN_OPERATION__ + 16
17 Foundation                     0x41940 __NSOQSchedule_f + 172
18 libdispatch.dylib              0x13114 _dispatch_block_async_invoke2 + 148
19 libdispatch.dylib              0x3f88 _dispatch_client_callout + 20
20 libdispatch.dylib              0x127f4 _dispatch_main_queue_drain + 928
21 libdispatch.dylib              0x12444 _dispatch_main_queue_callback_4CF + 44
22 CoreFoundation                 0x9a6c8 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 16
23 CoreFoundation                 0x7c02c __CFRunLoopRun + 2036
24 CoreFoundation                 0x80eb0 CFRunLoopRunSpecific + 612
25 GraphicsServices               0x1368 GSEventRunModal + 164
26 UIKitCore                      0x3a1668 -[UIApplication _run] + 888
27 UIKitCore                      0x3a12cc UIApplicationMain + 340
...
  1. getPageImageForPage the same as @a.protska posted above.

I am planning to submit a TSI request to Apple.

The same thing happened to me too. Is Apple acknowledging this to be a bug? Are there any plans to fix it? Is there a thread that mentions this issue more specifically?

Accepted Answer

I found out the cause and solved it. The problem is that when the print window is displayed, the result rendered by the UIPrintPageRenderer is previewed in real time. At this point, something crashes as rendering and previewing happen simultaneously. This is considered an API bug. The way to avoid it is not to render in real time in the print window, but to open the print window after setting the pre-rendered PDF file to printingItem before opening the print window. I didn't get any app crashes when I did this.

UIPrintInteractionController *controller = (UIPrintInteractionController*)m_pController;
CGSize pageSize = CGSizeMake(595.2, 841.8); // default A4
UIEdgeInsets pageMargins = UIEdgeInsetsMake(72, 72, 72,72);
CGRect printableRect = CGRectMake(pageMargins.left, pageMargins.top,
                                  pageSize.width - pageMargins.left - pageMargins.right,
                                  pageSize.height - pageMargins.top - pageMargins.bottom);

CGRect paperRect = CGRectMake(0, 0, pageSize.width, pageSize.height);

NSMutableData *pdfData = [NSMutableData data];
UIGraphicsBeginPDFContextToData( pdfData, paperRect, nil );
[self prepareForDrawingPages: NSMakeRange(0, self.numberOfPages)];
CGRect bounds = UIGraphicsGetPDFContextBounds();
for ( int i = 0 ; i < [self numberOfPages] ; i++ ) {
    UIGraphicsBeginPDFPage();        
    [self drawPageAtIndex: i inRect: bounds];
}
UIGraphicsEndPDFContext();

controller.printingItem = pdfdata;

With all of our apps where images are printed on multiple pages, we have seen a lot of crashes since iOS 16, but with iOS 16.6 it seems to have gotten much worse. We also have an iPad here that crashes every now and then or even several times in a row when printing. The crash happens in the print preview and we have no way to catch or prevent it. We are using UIPrintInteractionController with UIPrintPageRenderer, Objective C and minimum deployment target iOS 13.

On this iPad, also the “Photos” app sometimes crashes during the print preview when printing multiple images.

We created a test project in which we print 30 pages on which we draw random rectangles within the printableRect. In this test project, the app does not crash even with this iPad. We'll try drawing a picture instead of rectangles. Maybe then it will crash. We wanted to submit this test project to Apple with the crash description, but the test project did not generate the crash.

Stack trace 1:

Incident Identifier: B2BCB81B-4444-47F7-9D15-AAAAAAAAAAAAA
Hardware Model:      iPhone14,5
Process:             AAAAAAAAAAAAA [37220]
Path:                /private/var/containers/Bundle/Application/99AEC7F0-E7AB-4623-93F3-AAAAAAAAAAAAA/AAAAAAAAAAAAA.app/AAAAAAAAAAAAA
Identifier:          AAAAAAAAAAAAA.AAAAAAAAAAAAA.AAAAAAAAAAAAA
Version:             2.4 (1.0)
AppStoreTools:       14E221
AppVariant:          1:iPhone14,5:15
Code Type:           ARM-64 (Native)
Role:                Foreground
Parent Process:      launchd [1]
Coalition:           AAAAAAAAAAAAA.AAAAAAAAAAAAA.AAAAAAAAAAAAA [2071]

Date/Time:           2023-09-06 18:47:04.7501 -0400
Launch Time:         2023-09-06 18:43:02.3140 -0400
OS Version:          iPhone OS 16.6 (20G75)
Release Type:        User
Baseband Version:    2.80.01
Report Version:      104

Exception Type:  EXC_CRASH (SIGABRT)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Termination Reason: SIGNAL 6 Abort trap: 6
Terminating Process: AAAAAAAAAAAAA [37220]

Triggered by Thread:  0

Last Exception Backtrace:
0   CoreFoundation                	0x1d1de8cb4 __exceptionPreprocess + 164 (NSException.m:202)
1   libobjc.A.dylib               	0x1cae843d0 objc_exception_throw + 60 (objc-exception.mm:356)
2   Foundation                    	0x1cc57a54c -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 188 (NSException.m:242)
3   UIKitCore                     	0x1d45504f4 -[UICollectionView _Bug_Detected_In_Client_Of_UICollectionView_Invalid_Number_Of_Items_In_Section:] + 96 (UICollectionView.m:10074)
4   UIKitCore                     	0x1d415b5a8 -[UICollectionView _endItemAnimationsWithInvalidationContext:tentativelyForReordering:animator:collectionViewAnimator:] + 9916 (UICollectionView.m:9989)
5   UIKitCore                     	0x1d40b9d5c -[UICollectionView _updateRowsAtIndexPaths:updateAction:updates:] + 396 (UICollectionView.m:9346)
6   UIKitCore                     	0x1d40bb0e0 -[UICollectionView reloadItemsAtIndexPaths:] + 52 (UICollectionView.m:9366)
7   PrintKitUI                    	0x21b53d77c __55-[UIPrintPreviewViewController updatePrintPreviewInfo:]_block_invoke_3 + 80 (UIPrintPreviewViewController.m:348)
8   UIKitCore                     	0x1d3e7e494 +[UIView(Animation) performWithoutAnimation:] + 76 (UIView.m:14822)
9   PrintKitUI                    	0x21b53d6c8 __55-[UIPrintPreviewViewController updatePrintPreviewInfo:]_block_invoke + 580 (UIPrintPreviewViewController.m:347)
10  PrintKitUI                    	0x21b56eb30 -[UIPrintPreviewPageFetcher resetAllPages:] + 56 (UIPrintPreviewPageFetcher.m:589)
11  PrintKitUI                    	0x21b53d460 -[UIPrintPreviewViewController updatePrintPreviewInfo:] + 144 (UIPrintPreviewViewController.m:327)
12  PrintKitUI                    	0x21b55eb84 -[UIPrintPanelViewController updatePrintPreviewInfo] + 72 (UIPrintPanelViewController.m:537)
13  PrintKitUI                    	0x21b55cdb8 -[UIPrintPanelViewController observeValueForKeyPath:ofObject:change:context:] + 332 (UIPrintPanelViewController.m:258)
14  Foundation                    	0x1cc0d50d0 NSKeyValueNotifyObserver + 252 (NSKeyValueObserving.m:437)
15  Foundation                    	0x1cc0eb618 NSKeyValueDidChange + 356 (NSKeyValueObserving.m:556)
16  Foundation                    	0x1cc0d8518 -[NSObject(NSKeyValueObservingPrivate) _changeValueForKeys:count:maybeOldValuesDict:maybeNewValuesDict:usingBlock:] + 680 (NSKeyValueObserving.m:2661)
17  Foundation                    	0x1cc0d8248 -[NSObject(NSKeyValueObservingPrivate) _changeValueForKey:key:key:usingBlock:] + 64 (NSKeyValueObserving.m:2676)
18  Foundation                    	0x1cc0d77dc _NSSetObjectValueAndNotify + 284 (NSKeyValueObserverNotifying.m:111)
19  PrintKitUI                    	0x21b54e830 -[UIPrintPagesPerSheetOption listItemSelected:] + 280 (UIPrintLayoutOptions.m:311)
20  PrintKitUI                    	0x21b52e17c -[UIPrintOptionListViewController tableView:didSelectRowAtIndexPath:] + 116 (UIPrintOptionCells.m:107)
21  UIKitCore                     	0x1d4ce1334 -[UITableView _selectRowAtIndexPath:animated:scrollPosition:notifyDelegate:isCellMultiSelect:deselectPrevious:performCustomSelectionAction:] + 1196 (UITableView.m:9283)
22  UIKitCore                     	0x1d4ce1648 -[UITableView _userSelectRowAtPendingSelectionIndexPath:] + 256 (UITableView.m:9337)
23  UIKitCore                     	0x1d3fedca8 -[_UIAfterCACommitBlock run] + 72 (_UIAfterCACommitQueue.m:137)
24  UIKitCore                     	0x1d3fedbdc -[_UIAfterCACommitQueue flush] + 168 (_UIAfterCACommitQueue.m:228)
25  UIKitCore                     	0x1d3fedaf0 _runAfterCACommitDeferredBlocks + 496 (UIApplication.m:3249)
26  UIKitCore                     	0x1d3e8c428 _cleanUpAfterCAFlushAndRunDeferredBlocks + 108 (UIApplication.m:3213)
27  UIKitCore                     	0x1d434b4e4 _UIApplicationFlushCATransaction + 72 (UIApplication.m:3290)
28  UIKitCore                     	0x1d449bd94 _UIUpdateSequenceRun + 84 (_UIUpdateSequence.mm:114)
29  UIKitCore                     	0x1d4b00894 schedulerStepScheduledMainSection + 144 (_UIUpdateScheduler.m:1015)
30  UIKitCore                     	0x1d4affdf0 runloopSourceCallback + 92 (_UIUpdateScheduler.m:1164)
31  CoreFoundation                	0x1d1eb2128 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 28 (CFRunLoop.c:1957)
32  CoreFoundation                	0x1d1ebe7b4 __CFRunLoopDoSource0 + 176 (CFRunLoop.c:2001)
33  CoreFoundation                	0x1d1e435e8 __CFRunLoopDoSources0 + 244 (CFRunLoop.c:2038)
34  CoreFoundation                	0x1d1e590d4 __CFRunLoopRun + 828 (CFRunLoop.c:2953)
35  CoreFoundation                	0x1d1e5e3ec CFRunLoopRunSpecific + 612 (CFRunLoop.c:3418)
36  GraphicsServices              	0x20d37435c GSEventRunModal + 164 (GSEvent.c:2196)
37  UIKitCore                     	0x1d41eaf58 -[UIApplication _run] + 888 (UIApplication.m:3782)

Stack trace 2:

Incident Identifier: F335434E-C8BF-4EF1-8F60-AAAAAAAAAAAAA
Hardware Model:      iPhone12,5
Process:             AAAAAAAAAAAAA [16141]
Path:                /private/var/containers/Bundle/Application/441F63E7-002F-4405-97C8-AAAAAAAAAAAAA/AAAAAAAAAAAAA.app/AAAAAAAAAAAAA
Identifier:          AAAAAAAAAAAAA.AAAAAAAAAAAAA.AAAAAAAAAAAAA
Version:             2.3 (1.0)
AppStoreTools:       14E221
AppVariant:          1:iPhone12,5:15
Code Type:           ARM-64 (Native)
Role:                Foreground
Parent Process:      launchd [1]
Coalition:           AAAAAAAAAAAAA.AAAAAAAAAAAAA.AAAAAAAAAAAAA [2510]

Date/Time:           2023-07-13 09:48:24.8882 -0400
Launch Time:         2023-07-12 18:37:54.2619 -0400
OS Version:          iPhone OS 16.5.1 (20F75)
Release Type:        User
Baseband Version:    4.02.01
Report Version:      104

Exception Type:  EXC_BAD_ACCESS (SIGSEGV)
Exception Subtype: KERN_INVALID_ADDRESS at 0x0000000000000008
Exception Codes: 0x0000000000000001, 0x0000000000000008
VM Region Info: 0x8 is not in any region.  Bytes before following region: 68719476728
      REGION TYPE                 START - END      [ VSIZE] PRT/MAX SHRMOD  REGION DETAIL
      UNUSED SPACE AT START
--->  
      commpage (reserved)     1000000000-7000000000 [384.0G] ---/--- SM=NUL  ...(unallocated)
Termination Reason: SIGNAL 11 Segmentation fault: 11
Terminating Process: exc handler [16141]

Triggered by Thread:  0


Thread 0 name:
Thread 0 Crashed:
0   CoreGraphics                  	0x000000019c7e9d7c CGContextDrawPDFPageWithDrawingCallbacks + 116 (CGPDFPage.c:547)
1   CoreGraphics                  	0x000000019c787fbc CGContextDrawPDFPage + 36 (CGPDFPage.c:513)
2   PrintKitUI                    	0x00000001e43967e4 getPageImageForPage + 1632 (UIPrintPreviewHelper.m:0)
3   PrintKitUI                    	0x00000001e43b8b44 -[UIPrintPreviewPageFetcher _drawPageContextIntoImage:] + 296 (UIPrintPreviewPageFetcher.m:233)
4   PrintKitUI                    	0x00000001e43b83c8 -[UIPrintPreviewPageFetcher sheetImageForItemAt:] + 112 (UIPrintPreviewPageFetcher.m:129)
5   PrintKitUI                    	0x00000001e4389214 -[UIPrintPreviewViewController collectionView:cellForItemAtIndexPath:] + 132 (UIPrintPreviewViewController.m:491)
6   UIKitCore                     	0x000000019ce83a44 -[UICollectionView _createPreparedCellForItemAtIndexPath:withLayoutAttributes:applyAttributes:isFocused:notify:] + 980 (UICollectionView.m:3386)
7   UIKitCore                     	0x000000019d4340cc -[UICollectionView _createVisibleViewsForSingleCategoryAttributes:limitCreation:fadeForBoundsChange:] + 1120 (UICollectionView.m:5418)
8   UIKitCore                     	0x000000019d4343a4 -[UICollectionView _createVisibleViewsForAttributes:fadeForBoundsChange:notifyLayoutForVisibleCellsPass:] + 288 (UICollectionView.m:5483)
9   UIKitCore                     	0x000000019cd636dc -[UICollectionView _updateVisibleCellsNow:] + 1612 (UICollectionView.m:5005)
10  UIKitCore                     	0x000000019cd62fa0 -[UICollectionView layoutSubviews] + 304 (UICollectionView.m:6192)
11  UIKitCore                     	0x000000019cd3ebe0 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 1992 (UIView.m:18678)
12  QuartzCore                    	0x000000019c1f9074 CA::Layer::layout_if_needed(CA::Transaction*) + 500 (CALayer.mm:10311)
13  QuartzCore                    	0x000000019c20c5f0 CA::Layer::layout_and_display_if_needed(CA::Transaction*) + 148 (CALayer.mm:2519)
14  QuartzCore                    	0x000000019c21da1c CA::Context::commit_transaction(CA::Transaction*, double, double*) + 444 (CAContextInternal.mm:2714)
15  QuartzCore                    	0x000000019c24cff4 CA::Transaction::commit() + 648 (CATransactionInternal.mm:432)
16  QuartzCore                    	0x000000019c236f3c CA::Transaction::flush_as_runloop_observer(bool) + 88 (CATransactionInternal.mm:940)
17  CoreFoundation                	0x000000019ad5b234 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 36 (CFRunLoop.c:1789)
18  CoreFoundation                	0x000000019ace5410 __CFRunLoopDoObservers + 532 (CFRunLoop.c:1902)
19  CoreFoundation                	0x000000019ad4519c __CFRunLoopRun + 1028 (CFRunLoop.c:2981)
20  CoreFoundation                	0x000000019ad4a3ec CFRunLoopRunSpecific + 612 (CFRunLoop.c:3418)
21  GraphicsServices              	0x00000001d61e735c GSEventRunModal + 164 (GSEvent.c:2196)
22  UIKitCore                     	0x000000019d0d76e8 -[UIApplication _run] + 888 (UIApplication.m:3782)
23  UIKitCore                     	0x000000019d0d734c UIApplicationMain + 340 (UIApplication.m:5372)
24  AAAAAAAAAAAAA               	0x0000000104c1438c main + 80 (main.m:16)
25  dyld                          	0x00000001ba222dec start + 2220 (dyldMain.cpp:1165)

This is the output in the console that can be seen when the print preview crashes. But the same output appears at that moment even if the app does not crash. This probably has nothing to do with the crash.

2023-09-08 10:44:13.763186+0200 AAAAAAAAAAAAA[1250:306713] [LayoutConstraints] Unable to simultaneously satisfy constraints.
	Probably at least one of the constraints in the following list is one you don't want. 
	Try this: 
		(1) look at each constraint and try to figure out which you don't expect; 
		(2) find the code that added the unwanted constraint or constraints and fix it. 
(
    "<NSLayoutConstraint:0x280e58be0 V:|-(0)-[UIView:0x101a75210]   (active, names: '|':_UITableViewHeaderFooterContentView:0x101a74a00 )>",
    "<NSLayoutConstraint:0x280e58c30 UIView:0x101a75210.bottom == _UITableViewHeaderFooterContentView:0x101a74a00.bottom   (active)>",
    "<NSLayoutConstraint:0x280e58a00 UILabel:0x101a75f30.top == UIView:0x101a75210.topMargin   (active)>",
    "<NSLayoutConstraint:0x280e58dc0 UILabel:0x101a75f30.bottom == UIView:0x101a75210.bottomMargin   (active)>",
    "<NSLayoutConstraint:0x280e590e0 'UIView-bottomMargin-guide-constraint' V:[UILayoutGuide:0x2814271e0'UIViewLayoutMarginsGuide']-(8)-|   (active, names: '|':UIView:0x101a75210 )>",
    "<NSLayoutConstraint:0x280ea9720 'UIView-Encapsulated-Layout-Height' _UITableViewHeaderFooterContentView:0x101a74a00.height == 10   (active)>",
    "<NSLayoutConstraint:0x280e58d70 'UIView-topMargin-guide-constraint' V:|-(8)-[UILayoutGuide:0x2814271e0'UIViewLayoutMarginsGuide']   (active, names: '|':UIView:0x101a75210 )>"
)

Will attempt to recover by breaking constraint 
<NSLayoutConstraint:0x280e58dc0 UILabel:0x101a75f30.bottom == UIView:0x101a75210.bottomMargin   (active)>

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKitCore/UIView.h> may also be helpful.

We now have a simple test project with which we can cause the print preview to crash very often on a iPad Pro 12.9" 3. Generation with iOS 16.6. It often crashes when the print preview has finished "Gathering printer information". Call with a UIButton this action:

- (IBAction)print:(id)sender
{
    UIPrintInteractionController *printInteractionController = [UIPrintInteractionController sharedPrintController];
       
    UIPrintInfo *printInfo = [UIPrintInfo printInfo];
                
    printInfo.outputType = UIPrintInfoOutputGeneral;
                
    NSString* AppName = [[[NSBundle mainBundle] infoDictionary]   objectForKey:@"CFBundleName"];
    printInfo.jobName =  AppName;
    
    printInfo.duplex = UIPrintInfoDuplexNone;
         
    printInteractionController.printInfo = printInfo;
    
    printInteractionController.showsPaperSelectionForLoadedPapers = YES;
            
    UIPrintInteractionCompletionHandler completionHandler = ^(UIPrintInteractionController *printController, BOOL completed, NSError *error)
    {
        //
    };
    
    PrintPageRenderer *pageRenderer = [[PrintPageRenderer alloc]init];
    
    printInteractionController.delegate = pageRenderer;
    
    printInteractionController.printPageRenderer = pageRenderer;
    
    if([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad)
    {
        CGRect rect = CGRectMake(self.view.bounds.size.width/2, self.view.bounds.size.height/2, 1, 1);
        [printInteractionController presentFromRect:rect inView: self.view animated:YES
               completionHandler:completionHandler];
    }
    else
    {
        [printInteractionController presentAnimated:YES completionHandler:completionHandler];
    }
}

The PrintPageRenderer.h:


#import <UIKit/UIKit.h>


@interface PrintPageRenderer : UIPrintPageRenderer <UIPrintInteractionControllerDelegate>

@end

The PrintPageRenderer.m:

#import "PrintPageRenderer.h"

@implementation PrintPageRenderer

-(NSInteger)numberOfPages
{
    return 15;
}

- (void)drawPageAtIndex:(NSInteger)pageIndex inRect:(CGRect)printableRect
{
    for (int i = 0; i< 1000; i++)
    {
        [[self randomColor] setFill];
        UIRectFill([self randomRectWithinPrintableRect:printableRect]);
    }
}

-(CGRect) randomRectWithinPrintableRect:(CGRect) printableRect
{
    CGFloat randomWidth = arc4random_uniform((uint32_t)CGRectGetWidth(printableRect));
    CGFloat randomHeight = arc4random_uniform((uint32_t)CGRectGetHeight(printableRect));
    CGFloat randomX = CGRectGetMinX(printableRect) + arc4random_uniform((uint32_t)(CGRectGetWidth(printableRect) - randomWidth));
    CGFloat randomY = CGRectGetMinY(printableRect) + arc4random_uniform((uint32_t)(CGRectGetHeight(printableRect) - randomHeight));
    CGRect randomRect = CGRectMake(randomX, randomY, randomWidth, randomHeight);
    return randomRect;
}

-(UIColor *)randomColor
{
    CGFloat red = (CGFloat)arc4random_uniform(256) / 255.0;
    CGFloat green = (CGFloat)arc4random_uniform(256) / 255.0;
    CGFloat blue = (CGFloat)arc4random_uniform(256) / 255.0;
    return [UIColor colorWithRed:red green:green blue:blue alpha:1.0];
}

@end

On an old iPhone 6s with iOS 15.7.8, this code works without problems and the print preview does not crash. But the print preview crashes on an iPhone 11 Pro Max with iOS 16.6. It's clearly an iOS 16 issue.

The problem seems to have been fixed in iOS 17. The code I posted above no longer crashes on iOS 17.

Hi, @webd . The workaround you described works like a charm. After implementing it, there have been almost no crashes on iOS 16.* related to PDF printing. Thanks a lot!

It's not just iOS 16, every version will crash

Crash when presenting UIPrintInteractionController on iOS 16
 
 
Q