How to Present a UIDocumentInteractionController from a SwiftUI View

1k views Asked by At

I have the following code that takes a screen shot of a SwiftUI View and I would like to present this screen shot in a UIDocumentInteractionController. I have done this in a UIKit ViewController and I would like to know if there is a way to convert the non-working code that I have to something that can present the UIDocumentInteractionController:

import SwiftUI

struct ContentView: View {
    let documentInteractionController = UIDocumentInteractionController()
    var body: some View {
        VStack {
            SharableView()
            Button(action: {
                let vc = UIHostingController(rootView: SharableView())
                vc.view.frame = CGRect(x: 0, y: 0, width: 400, height: 400)
                if let screenshot = vc.view.makeSnapshot() {
                    if let data = screenshot.pngData() {
                        let filename = getDocumentsDirectory().appendingPathComponent("ScreenShot.png")
                        try? data.write(to: filename)
                        documentInteractionController.uti = "public.image"
                        documentInteractionController.url = filename
                        documentInteractionController.presentOptionsMenu(from: vc.view.bounds, in: vc.view, animated: true)
                    }
                }
            }, label: {
                Text("Share")
            })
        }
    }
}

struct SharableView: View {
    var body: some View {
        Text("Hello, world!")
            .padding()
    }
}

func getDocumentsDirectory() -> URL {
    let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    return paths[0]
}

extension UIView {
    func makeSnapshot() -> UIImage? {
        let renderer = UIGraphicsImageRenderer(size: frame.size)
        return renderer.image { _ in drawHierarchy(in: bounds, afterScreenUpdates: true) }
    }
}

This gives me an error which makes sense. But I do not know how to fix it. What's the right parameters to pass into documentInteractionController.presentOptionsMenu(...)?

[Presentation] Attempt to present <_UIDICActivityViewController: 0x7f84e1024400> on <_TtGC7SwiftUI19UIHostingControllerV9testShare12SharableView_: 0x7f84e2906d70> (from <_TtGC7SwiftUI19UIHostingControllerV9testShare12SharableView_: 0x7f84e2906d70>) whose view is not in the window hierarchy.
0

There are 0 answers