katzer / cordova-plugin-printer

Print HTML documents
Apache License 2.0
310 stars 284 forks source link

Unable to PrintToPrinter in IOS15 #281

Open AlisterRWood opened 2 years ago

AlisterRWood commented 2 years ago

Hi Katzer, thanks so much for creating this plugin.. it's been fantastic.

Sadly since IOS 15 came out the printToPrinter function now throws an error

'Application tried to present modally a view controller <UIAlertController: 0x7fd9c205f000> that is already being presented by <UIViewController: 0x7fd9c0c139f0>.'

It can print using the picker controller but we need the silent printing options as it's customer facing.

Any help with this would be greatly appreciated

kloopler commented 2 years ago

What resolved the crash for me was to edit UIPrintInteractionController+APPPrinter.m and wrap the ctrl.printInfo assignment with a dispatch_async as shown below.

dispatch_async(dispatch_get_main_queue(), ^{ ctrl.printInfo = [APPPrinterInfo printInfoWithDictionary:settings]; });

AlisterRWood commented 2 years ago

Thank you Kloopler, I'll give that a try 👍

AlisterRWood commented 2 years ago

That's a shame.. it didn't work for me

Screen Shot 2021-10-22 at 12 24 40 pm
AlisterRWood commented 2 years ago

Hi @kloopler, would you be so kind as to share the code you have in the UIPrintInteractionController+APPPrinter.m file?

legustav commented 2 years ago

Hi @AlisterRWood were you able to sort this error? we´re having the same issue and haven't found a fix yet.

AlisterRWood commented 2 years ago

Sadly not... I tried wrapping nearly part of each function in a dispatch_async but never got it working. Let me know if you find anything that does work and I'll let you know if I do

legustav commented 2 years ago

Thanks @AlisterRWood we´ll let you know for sure. @kloopler would you be so kind to share the code in your UIPrintInteractionController+APPPrinter.m file? it will be very helpful

Fauphi commented 2 years ago

Hi @legustav & @AlisterRWood,

looks like this is a general problem in iOS15: https://developer.apple.com/forums/thread/689876

You need to update APPPrinter.m (l.259) like this to make it work again:

dispatch_async(dispatch_get_main_queue(), ^{
        // [ctrl printToPrinter:printer completionHandler:
        //  ^(UIPrintInteractionController *ctrl, BOOL ok, NSError *e) {
        //      [self rememberPrinter:(ok ? printer : NULL)];
        //      [self sendResultWithMessageAsBool:ok callbackId:callbackId];
        //  }];
        [printer contactPrinter:^(BOOL available) {                 
            if (available) {                     
                [ctrl printToPrinter:printer completionHandler:
                ^(UIPrintInteractionController *ctrl, BOOL ok, NSError *e) {
                    [self rememberPrinter:(ok ? printer : NULL)];
                    [self sendResultWithMessageAsBool:ok callbackId:callbackId];
                }];                 
            } else {
                NSLog(@"printer unavailable");
            }
        }];
    });
AlisterRWood commented 2 years ago

Thank you so much @Fauphi. That has got my app up and running again

legustav commented 2 years ago

Many thanks @Fauphi @kloopler & @AlisterRWood for all the help!

jameshhood commented 2 years ago

I am getting similar errors

2022-04-29 18:49:21.050708-0400 POD[74776:2515552] [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. 
    (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints) 
(
    "<NSAutoresizingMaskLayoutConstraint:0x600003f4e3f0 h=--& v=--& UIView:0x7f7dbd730400.width == 198.591   (active)>",
    "<NSLayoutConstraint:0x600003f540a0 UIView:0x7f7dbd730400.leading == UIPrintPreviewPageCell:0x7f7dbd72bb50.leading   (active)>",
    "<NSLayoutConstraint:0x600003f54c30 UIView:0x7f7dbd730400.trailing == UIPrintPreviewPageCell:0x7f7dbd72bb50.trailing   (active)>",
    "<NSLayoutConstraint:0x600003f854a0 'UIView-Encapsulated-Layout-Width' UIPrintPreviewPageCell:0x7f7dbd72bb50.width == 198.333   (active)>"
)

Will attempt to recover by breaking constraint 
<NSLayoutConstraint:0x600003f54c30 UIView:0x7f7dbd730400.trailing == UIPrintPreviewPageCell:0x7f7dbd72bb50.trailing   (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.

If I start a print I get this warning above. If I cancel and hit my print button again my app crashes and I get the following

2022-04-29 18:50:39.151016-0400 POD[74776:2521443] [Animation] +[UIView setAnimationsEnabled:] being called from a background thread. Performing any operation from a background thread on UIView or a subclass is not supported and may result in unexpected and insidious behavior. trace=(
    0   UIKitCore                           0x000000012e17c8fa kFixedAnimationDuration_block_invoke_4 + 119
    1   libdispatch.dylib                   0x000000010cbcfa5b _dispatch_client_callout + 8
    2   libdispatch.dylib                   0x000000010cbd0f24 _dispatch_once_callout + 66
    3   UIKitCore                           0x000000012e17c9d5 +[UIView(Animation) performWithoutAnimation:] + 78
    4   UIKitCore                           0x000000012d2277d1 -[UICollectionView _updateWithItems:tentativelyForReordering:propertyAnimator:collectionViewAnimator:] + 4177
    5   UIKitCore                           0x000000012d21ef18 -[UICollectionView _endItemAnimationsWithInvalidationContext:tentativelyForReordering:animator:collectionViewAnimator:] + 15362
    6   UIKitCore                           0x000000012d21a48a -[UICollectionView _updateRowsAtIndexPaths:updateAction:updates:] + 510
    7   UIKitCore                           0x000000012d21a614 -[UICollectionView reloadItemsAtIndexPaths:] + 62
    8   UIKitCore                           0x000000012db6524b -[UIPrintPreviewViewController updatePrintPreviewInfo:] + 131
    9   UIKitCore                           0x000000012db5f779 -[UIPrintPanelViewController updatePrintPreviewInfo] + 94
    10  CoreFoundation                      0x000000010ba71331 __CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ + 12
    11  CoreFoundation                      0x000000010ba712f7 ___CFXRegistrationPost_block_invoke + 49
    12  CoreFoundation                      0x000000010ba70844 _CFXRegistrationPost + 496
    13  CoreFoundation                      0x000000010ba7017a _CFXNotificationPost + 822
    14  Foundation                          0x0000000107c05dec -[NSNotificationCenter postNotificationName:object:userInfo:] + 82
    15  UIKitCore                           0x000000012db8591f -[UIPrintInfo setOutputType:] + 78
    16  CordovaPlugins                      0x00000001064ee61a +[APPPrinterInfo printInfoWithDictionary:] + 762
    17  CordovaPlugins                      0x00000001064f6c98 +[UIPrintInteractionController(APPPrinter) sharedPrintControllerWithSettings:] + 136
    18  CordovaPlugins                      0x00000001064ebcd6 -[APPPrinter printContent:withSettings:] + 182
    19  CordovaPlugins                      0x00000001064eb3bd __20-[APPPrinter print:]_block_invoke + 269
    20  libdispatch.dylib                   0x000000010cbce816 _dispatch_call_block_and_release + 12
    21  libdispatch.dylib                   0x000000010cbcfa5b _dispatch_client_callout + 8
    22  libdispatch.dylib                   0x000000010cbd1e63 _dispatch_queue_override_invoke + 1040
    23  libdispatch.dylib                   0x000000010cbe1ba2 _dispatch_root_queue_drain + 419
    24  libdispatch.dylib                   0x000000010cbe264e _dispatch_worker_thread2 + 196
    25  libsystem_pthread.dylib             0x00007fff6fb05f8a _pthread_wqthread + 256
    26  libsystem_pthread.dylib             0x00007fff6fb04f57 start_wqthread + 15
)
2022-04-29 18:50:39.156101-0400 POD[74776:2521443] This application is modifying the autolayout engine from a background thread after the engine was accessed from the main thread. This can lead to engine corruption and weird crashes.
 Stack:(
    0   CoreAutoLayout                      0x000000010f9e3f0c _AssertAutoLayoutOnAllowedThreadsOnly + 206
    1   CoreAutoLayout                      0x000000010f9e426c -[NSISEngine withBehaviors:performModifications:] + 25
    2   UIKitCore                           0x000000012e079fb3 -[UIView(UIConstraintBasedLayout) _engineHostConstraints_frameDidChange] + 284
    3   UIKitCore                           0x000000012e07a05b -[UIView _constraints_frameDidChange] + 159
    4   UIKitCore                           0x000000012e1652d9 -[UIView setCenter:] + 358
    5   UIKitCore                           0x000000012d23f713 -[UICollectionReusableView _setLayoutAttributes:] + 307
    6   UIKitCore                           0x000000012d242eea -[UICollectionViewCell _setLayoutAttributes:] + 147
    7   UIKitCore                           0x000000012d1ff1f1 -[UICollectionView _applyLayoutAttributes:toView:] + 170
    8   UIKitCore                           0x000000012d217420 __88-[UICollectionView _dequeueReusableViewOfKind:withIdentifier:forIndexPath:viewCategory:]_block_invoke_2 + 35
    9   UIKitCore                           0x000000012e17c9db +[UIView(Animation) performWithoutAnimation:] + 84
    10  UIKitCore                           0x000000012d217034 -[UICollectionView _dequeueReusableViewOfKind:withIdentifier:forIndexPath:viewCategory:] + 2147
    11  UIKitCore                           0x000000012d2174e8 -[UICollectionView dequeueReusableCellWithReuseIdentifier:forIndexPath:] + 88
    12  UIKitCore                           0x000000012db65a51 -[UIPrintPreviewViewController collectionView:cellForItemAtIndexPath:] + 65
    13  UIKitCore                           0x000000012d1fd848 -[UICollectionView _createPreparedCellForItemAtIndexPath:withLayoutAttributes:applyAttributes:isFocused:notify:] + 1241
    14  UIKitCore                           0x000000012d1fd2f8 -[UICollectionView _preparedCellForItemAtIndexPath:withLayoutAttributes:applyAttributes:isFocused:notify:] + 731
    15  UIKitCore                           0x000000012d22412d __78-[UICollectionView _viewAnimationsForCurrentUpdateWithCollectionViewAnimator:]_block_invoke.2009 + 578
    16  UIKitCore                           0x000000012d220b9e -[UICollectionView _viewAnimationsForCurrentUpdateWithCollectionViewAnimator:] + 4411
    17  UIKitCore                           0x000000012d228b75 __102-[UICollectionView _updateWithItems:tentativelyForReordering:propertyAnimator:collectionViewAnimator:]_block_invoke.2103 + 258
    18  UIKitCore                           0x000000012e17c9db +[UIView(Animation) performWithoutAnimation:] + 84
    19  UIKitCore                           0x000000012d2277d1 -[UICollectionView _updateWithItems:tentativelyForReordering:propertyAnimator:collectionViewAnimator:] + 4177
    20  UIKitCore                           0x000000012d21ef18 -[UICollectionView _endItemAnimationsWithInvalidationContext:tentativelyForReordering:animator:collectionViewAnimator:] + 15362
    21  UIKitCore                           0x000000012d21a48a -[UICollectionView _updateRowsAtIndexPaths:updateAction:updates:] + 510
    22  UIKitCore                           0x000000012d21a614 -[UICollectionView reloadItemsAtIndexPaths:] + 62
    23  UIKitCore                           0x000000012db6524b -[UIPrintPreviewViewController updatePrintPreviewInfo:] + 131
    24  UIKitCore                           0x000000012db5f779 -[UIPrintPanelViewController updatePrintPreviewInfo] + 94
    25  CoreFoundation                      0x000000010ba71331 __CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ + 12
    26  CoreFoundation                      0x000000010ba712f7 ___CFXRegistrationPost_block_invoke + 49
    27  CoreFoundation                      0x000000010ba70844 _CFXRegistrationPost + 496
    28  CoreFoundation                      0x000000010ba7017a _CFXNotificationPost + 822
    29  Foundation                          0x0000000107c05dec -[NSNotificationCenter postNotificationName:object:userInfo:] + 82
    30  UIKitCore                           0x000000012db8591f -[UIPrintInfo setOutputType:] + 78
    31  CordovaPlugins                      0x00000001064ee61a +[APPPrinterInfo printInfoWithDictionary:] + 762
    32  CordovaPlugins                      0x00000001064f6c98 +[UIPrintInteractionController(APPPrinter) sharedPrintControllerWithSettings:] + 136
    33  CordovaPlugins                      0x00000001064ebcd6 -[APPPrinter printContent:withSettings:] + 182
    34  CordovaPlugins                      0x00000001064eb3bd __20-[APPPrinter print:]_block_invoke + 269
    35  libdispatch.dylib                   0x000000010cbce816 _dispatch_call_block_and_release + 12
    36  libdispatch.dylib                   0x000000010cbcfa5b _dispatch_client_callout + 8
    37  libdispatch.dylib                   0x000000010cbd1e63 _dispatch_queue_override_invoke + 1040
    38  libdispatch.dylib                   0x000000010cbe1ba2 _dispatch_root_queue_drain + 419
    39  libdispatch.dylib                   0x000000010cbe264e _dispatch_worker_thread2 + 196
    40  libsystem_pthread.dylib             0x00007fff6fb05f8a _pthread_wqthread + 256
    41  libsystem_pthread.dylib             0x00007fff6fb04f57 start_wqthread + 15
)
2022-04-29 18:50:39.161411-0400 POD[74776:2521443] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Modifications to the layout engine must not be performed from a background thread after it has been accessed from the main thread.'
*** First throw call stack:
(
    0   CoreFoundation                      0x000000010bb32d44 __exceptionPreprocess + 242
    1   libobjc.A.dylib                     0x00000001064aca65 objc_exception_throw + 48
    2   CoreAutoLayout                      0x000000010f9e3fe4 -[NSISEngine tryToOptimizeReturningMutuallyExclusiveConstraints] + 0
    3   CoreAutoLayout                      0x000000010f9e426c -[NSISEngine withBehaviors:performModifications:] + 25
    4   UIKitCore                           0x000000012e079fb3 -[UIView(UIConstraintBasedLayout) _engineHostConstraints_frameDidChange] + 284
    5   UIKitCore                           0x000000012e07a05b -[UIView _constraints_frameDidChange] + 159
    6   UIKitCore                           0x000000012e1652d9 -[UIView setCenter:] + 358
    7   UIKitCore                           0x000000012d23f713 -[UICollectionReusableView _setLayoutAttributes:] + 307
    8   UIKitCore                           0x000000012d242eea -[UICollectionViewCell _setLayoutAttributes:] + 147
    9   UIKitCore                           0x000000012d1ff1f1 -[UICollectionView _applyLayoutAttributes:toView:] + 170
    10  UIKitCore                           0x000000012d217420 __88-[UICollectionView _dequeueReusableViewOfKind:withIdentifier:forIndexPath:viewCategory:]_block_invoke_2 + 35
    11  UIKitCore                           0x000000012e17c9db +[UIView(Animation) performWithoutAnimation:] + 84
    12  UIKitCore                           0x000000012d217034 -[UICollectionView _dequeueReusableViewOfKind:withIdentifier:forIndexPath:viewCategory:] + 2147
    13  UIKitCore                           0x000000012d2174e8 -[UICollectionView dequeueReusableCellWithReuseIdentifier:forIndexPath:] + 88
    14  UIKitCore                           0x000000012db65a51 -[UIPrintPreviewViewController collectionView:cellForItemAtIndexPath:] + 65
    15  UIKitCore                           0x000000012d1fd848 -[UICollectionView _createPreparedCellForItemAtIndexPath:withLayoutAttributes:applyAttributes:isFocused:notify:] + 1241
    16  UIKitCore                           0x000000012d1fd2f8 -[UICollectionView _preparedCellForItemAtIndexPath:withLayoutAttributes:applyAttributes:isFocused:notify:] + 731
    17  UIKitCore                           0x000000012d22412d __78-[UICollectionView _viewAnimationsForCurrentUpdateWithCollectionViewAnimator:]_block_invoke.2009 + 578
    18  UIKitCore                           0x000000012d220b9e -[UICollectionView _viewAnimationsForCurrentUpdateWithCollectionViewAnimator:] + 4411
    19  UIKitCore                           0x000000012d228b75 __102-[UICollectionView _updateWithItems:tentativelyForReordering:propertyAnimator:collectionViewAnimator:]_block_invoke.2103 + 258
    20  UIKitCore                           0x000000012e17c9db +[UIView(Animation) performWithoutAnimation:] + 84
    21  UIKitCore                           0x000000012d2277d1 -[UICollectionView _updateWithItems:tentativelyForReordering:propertyAnimator:collectionViewAnimator:] + 4177
    22  UIKitCore                           0x000000012d21ef18 -[UICollectionView _endItemAnimationsWithInvalidationContext:tentativelyForReordering:animator:collectionViewAnimator:] + 15362
    23  UIKitCore                           0x000000012d21a48a -[UICollectionView _updateRowsAtIndexPaths:updateAction:updates:] + 510
    24  UIKitCore                           0x000000012d21a614 -[UICollectionView reloadItemsAtIndexPaths:] + 62
    25  UIKitCore                           0x000000012db6524b -[UIPrintPreviewViewController updatePrintPreviewInfo:] + 131
    26  UIKitCore                           0x000000012db5f779 -[UIPrintPanelViewController updatePrintPreviewInfo] + 94
    27  CoreFoundation                      0x000000010ba71331 __CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ + 12
    28  CoreFoundation                      0x000000010ba712f7 ___CFXRegistrationPost_block_invoke + 49
    29  CoreFoundation                      0x000000010ba70844 _CFXRegistrationPost + 496
    30  CoreFoundation                      0x000000010ba7017a _CFXNotificationPost + 822
    31  Foundation                          0x0000000107c05dec -[NSNotificationCenter postNotificationName:object:userInfo:] + 82
    32  UIKitCore                           0x000000012db8591f -[UIPrintInfo setOutputType:] + 78
    33  CordovaPlugins                      0x00000001064ee61a +[APPPrinterInfo printInfoWithDictionary:] + 762
    34  CordovaPlugins                      0x00000001064f6c98 +[UIPrintInteractionController(APPPrinter) sharedPrintControllerWithSettings:] + 136
    35  CordovaPlugins                      0x00000001064ebcd6 -[APPPrinter printContent:withSettings:] + 182
    36  CordovaPlugins                      0x00000001064eb3bd __20-[APPPrinter print:]_block_invoke + 269
    37  libdispatch.dylib                   0x000000010cbce816 _dispatch_call_block_and_release + 12
    38  libdispatch.dylib                   0x000000010cbcfa5b _dispatch_client_callout + 8
    39  libdispatch.dylib                   0x000000010cbd1e63 _dispatch_queue_override_invoke + 1040
    40  libdispatch.dylib                   0x000000010cbe1ba2 _dispatch_root_queue_drain + 419
    41  libdispatch.dylib                   0x000000010cbe264e _dispatch_worker_thread2 + 196
    42  libsystem_pthread.dylib             0x00007fff6fb05f8a _pthread_wqthread + 256
    43  libsystem_pthread.dylib             0x00007fff6fb04f57 start_wqthread + 15
)
libc++abi: terminating with uncaught exception of type NSException
dyld4 config: DYLD_ROOT_PATH=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot DYLD_LIBRARY_PATH=/Users/jhood/Library/Developer/Xcode/DerivedData/App-caaykzrtdthsjadiokzfwhamtbls/Build/Products/Debug-iphonesimulator:/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/usr/lib/system/introspection DYLD_INSERT_LIBRARIES=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/usr/lib/libBacktraceRecording.dylib:/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/usr/lib/libMainThreadChecker.dylib:/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/Developer/Library/PrivateFrameworks/DTDDISupport.framework/libViewDebuggerSupport.dylib DYLD_FRAMEWORK_PATH=/Users/jhood/Library/Developer/Xcode/DerivedData/App-caaykzrtdthsjadiokzfwhamtbls/Build/Products/Debug-iphonesimulator
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Modifications to the layout engine must not be performed from a background thread after it has been accessed from the main thread.'
terminating with uncaught exception of type NSException
CoreSimulator 802.6 - Device: iPhone 12 Pro Max (3B3E9877-7929-4BC9-857F-CEE733E97B6C) - Runtime: iOS 15.4 (19E240) - DeviceType: iPhone 12 Pro Max
(lldb) 

I'm going to keep trying some other things but this used to work just fine. The only thing that has changed I believe is iOS15

kloopler commented 2 years ago

Apologies for the late reply. My app began crashing again after I updated to iPadOS v15.4.1. I found a work around that is a bit of a hack but it stopped the crashing. Here it is below. Basically runs [UIPrintInteractionController sharedPrintControllerWithSettings:settings] on the main thread. @jameshhood hope this points you in the right direction

` - (void) printContent:(NSString )content withSettings:(NSDictionary )settings { __block id item;

__block UIPrintInteractionController* ctrl;
//UIPrintInteractionController* ctrl =
//[UIPrintInteractionController sharedPrintControllerWithSettings:settings];

dispatch_sync(dispatch_get_main_queue(), ^{
    ctrl =
    [UIPrintInteractionController sharedPrintControllerWithSettings:settings];
});`
dimer47 commented 1 year ago

@kloopler Your solution works perfectly fine! Thanks a lot. ❤️ Can you push a merge request? cc @katzer

dimer47 commented 1 year ago

I created a PR by taking the fix of @kloopler : https://github.com/katzer/cordova-plugin-printer/pull/292

bilalsaeed commented 1 year ago

@jameshhood did you manage to resolve this issue?