0

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.
Dogahe
  • 1,380
  • 2
  • 20
  • 50
  • 1
    The following should be helpful https://stackoverflow.com/a/60421084/12299030. – Asperi Oct 04 '20 at 05:43
  • I guess the part I can't wrap my head around is since documentInteractionController needs the url and in my case url created based on a file saved from a SwiftUI snapshot I am not sure at what point I need to create the file and pass it to documentInteractionController.url. – Dogahe Oct 06 '20 at 01:48

0 Answers0