SwiftUI [ShareSheet] connection invalidated. Attempt to present which is already presenting

1.4k Views Asked by At

I'm trying to create a share button in my app. App on SwiftUi, Xcode version 13.2.1, iPhone 15.2

If I use this code:

let url = URL(string: "https://example.com")
let activityController = UIActivityViewController(activityItems: [url!], applicationActivities: nil)                        
UIApplication.shared.windows.first?.rootViewController!.present(activityController, animated: true, completion: nil)

This is the error:

[Presentation] Attempt to present <UIActivityViewController: 0x7feb1600e600> on <TtGC7SwiftUI19UIHostingControllerGVS_15ModifiedContentVS_7AnyViewVS_12RootModifier_: 0x7feb16a05430> (from <TtGC7SwiftUI19UIHostingControllerGVS_15ModifiedContentVS_7AnyViewVS_12RootModifier_: 0x7feb16a05430>) which is already presenting <TtGC7SwiftUI29PresentationHostingControllerVS_7AnyView: 0x7feb05f142e0>.

I understand that it is already presenting, but I don't understand how you can get around it.

If I use this combination of:

If I add a .presentedViewController? and get this combination, the share button works, but only on iPhone and there are a lot of errors in the console, on iPad the application crashes completely.

UIApplication.shared.windows.first?.rootViewController!.presentedViewController?.present(activityController, animated: true, completion: nil)

Can you tell me how to get around this problem?

1

There are 1 best solutions below

1
Ostap Suleymanovich On

I was able to solve the problem using this answer. Perhaps it will be of use to someone, as it was to me.

By changing one line

source.present(activityVC, animated: true)

to this

source.presentedViewController?.present(activityVC, animated: true)