2

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.

Noob
  • 133
  • 6
  • 1
    Found the solution here. Basically needed the Top Most View. https://stackoverflow.com/questions/26667009/get-top-most-uiviewcontroller/26667122#26667122 – Noob May 06 '21 at 19:55

0 Answers0