Display Share Sheet (UIActivityViewController) in a Modal .sheet() in SwiftUI

52 Views Asked by At

I am trying to display a Share Sheet from inside a Modal .sheet() in SwiftUI.

enter image description here

The Share Sheet does not display; and I get the following error:

[Presentation] Attempt to present <UIActivityViewController: 0x105012200> on <_TtGC7SwiftUI19UIHostingControllerGVS_15ModifiedContentVS_7AnyViewVS_12RootModifier__: 0x10110b070> (from <_TtGC7SwiftUI19UIHostingControllerGVS_15ModifiedContentVS_7AnyViewVS_12RootModifier__: 0x10110b070>) which is already presenting <_TtGC7SwiftUI29PresentationHostingControllerVS_7AnyView_: 0x1038060d0>.
[ShareSheet] connection invalidated

How can I make it display from the .sheet()

This is my code:

import SwiftUI

struct ContentView: View {
    
    @State private var displayModal = false
    
    var body: some View {
        VStack {
            Button("1. Share Sheet") {
                shareSheet()
            }.padding()
            
            Button("2. Modal Sheet") {
                displayModal.toggle()
            }
            .sheet(isPresented: $displayModal) {
                Button("3. Inside Modal Sheet") {
                    shareSheet()
                }
            }
            .padding()
        }
        
    }
    
    func shareSheet() {
        let items: [Any] = ["Share My App", URL(string: "https://www.apple.com")!]
        let ac = UIActivityViewController(activityItems: items, applicationActivities: nil)
        UIApplication.shared.windows.first?.rootViewController?.present(ac, animated: true, completion: nil)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Thanks, guys.

0

There are 0 best solutions below