Shawn Frank
Shawn Frank

Reputation: 5213

Get notified when PKToolPicker is visible in QLPreviewController

I currently show a QLPreviewController in a SwiftUI app using a UIViewControllerRepresentable - here is the code:

struct QLPDFPreviewController: UIViewControllerRepresentable {
    let url: URL?
    
    func makeUIViewController(context: Context) -> UINavigationController {
        let controller = QLPreviewController()
        controller.dataSource = context.coordinator
        controller.delegate = context.coordinator
        let navigationController = UINavigationController(rootViewController: controller)
        return navigationController
    }
    
    func updateUIViewController(_ uiViewController: UINavigationController,
                                context: Context) { }
    
    func makeCoordinator() -> Coordinator {
        return Coordinator(parent: self)
    }
    
    class Coordinator: NSObject, QLPreviewControllerDataSource, QLPreviewControllerDelegate {
        let parent: QLPDFPreviewController
        
        init(parent: QLPDFPreviewController) {
            self.parent = parent
        }
        
        func numberOfPreviewItems(in controller: QLPreviewController) -> Int {
            return 1
        }
        
        func previewController(_ controller: QLPreviewController,
                               previewItemAt index: Int) -> QLPreviewItem {
            guard let url = parent.url else { return NSURL(string: "")! }
            return url as NSURL
        }
        
        func previewController(_ controller: QLPreviewController,
                               editingModeFor previewItem: QLPreviewItem) -> QLPreviewItemEditingMode {
            .updateContents
        }
    }
}

I use this to display a PDF and using the QLPreviewController the user can input text into the PDF and draw on the PDF.

Everything works fine in terms of functionality. I now have a requirement to do some processing when either the keyboard has opened or the PKToolPicker is open within the QLPreviewController.

Listening for keyboard events is fine as I could use the UIResponder.keyboardWillShowNotification notification, however, I could not find something similar to get notified when the PKToolPicker is open.

I did come across func toolPickerVisibilityDidChange(PKToolPicker) in the documentation, however, it seems like we can only use this if we initialize our own PKToolPicker.

Is there any generic way to listen to whether a PKToolPicker is visible similar to something we do for the keyboard ?

Upvotes: 1

Views: 125

Answers (0)

Related Questions