UIPrintInteractionController crashed in iOS 14, It's working fine on iOS 13 (Tried to obtain the web lock from a thread)

Viewed 556
    @objc func printData(){
    let pic = UIPrintInteractionController.shared

    let printInfo : UIPrintInfo = UIPrintInfo(dictionary: nil)
    printInfo.outputType = UIPrintInfo.OutputType.general
    pic.printInfo = printInfo
    pic.printFormatter = self.webViewPrint.viewPrintFormatter()

    pic.present(animated: true, completionHandler: nil)
}

Present working fine, app crashing when I have dismissing this view controller.

"webViewPrint" is a UIWebView

App crash log: 2020-09-25 12:20:19.399922+0530 void _WebThreadLock(), 0x13b425020: Tried to obtain the web lock from a thread other than the main thread or the web thread. This may be a result of calling to UIKit from a secondary thread. Crashing now...

2 Answers

Try

    DispatchQueue.main.async {
pic.present(animated: true, completionHandler: nil)

    }

From the error it seems UI stuff is happening on secondary thread, doing it on main thread should fix it.

While this crash is quite hard to pin down, I would recommend following Apple's pretty aggressive warning messages when submitting to AppstoreConnect:

ITMS-90809: Deprecated API Usage 
App updates that use UIWebView will no longer be accepted as of December 2020. 
Instead, use WKWebView for improved security and reliability. 
Learn more (https://developer.apple.com/documentation/uikit/uiwebview).

I had been putting off the migration and also ran into the exact same crash in iOS14. Converting everything from UIWebView -> WKWebView did the trick for me.

So in the case for your code, you simply need to swap the instance of webViewPrint and should no longer see the crashes.

var webViewPrint = WKWebView(frame: .zero)
Related