1

I'm trying to present a share sheet using the code below. It works fine on iPhones, but crashes on iPad (both in the simulator and on a real device).

The crash gives the following message:

Thread 1: "UIPopoverPresentationController (<UIPopoverPresentationController: 0x7fedaa285c80>) should have a non-nil sourceView or barButtonItem set before the presentation occurs."

I think it might have to do with the issues mentioned here, but I'm not sure how to incorporate the solutions they discuss into my code.

import SwiftUI

struct ContentView: View {
    var body: some View {
        Button(action: showSheet) {
            Text("Show sheet")
        }
    }
    
    func showSheet() {
        guard let data = URL(string: "https://www.google.com") else { return }
        let sheet = UIActivityViewController(activityItems: [data], applicationActivities: nil)
        UIApplication.shared.windows.first?.rootViewController?.present(sheet, animated: true, completion: nil)
    }
}
sia
  • 256
  • 3
  • 14
  • 1
    Generally, if you have a crash, you want to mention what the error message is when asking on SO. I can infer from experience that it's *probably* a message about `modalPresentationStyle` -- is this correct? There are plenty of examples of using `UIActivityViewController` in SwiftUI here: https://stackoverflow.com/questions/56533564/showing-uiactivityviewcontroller-in-swiftui – jnpdx May 27 '21 at 22:17
  • Sorry about that - just added the error message to my question. I'll check out the link you shared as well. – sia May 27 '21 at 22:25
  • 1
    Does this answer your question? [Presenting UIActivityViewController from SwiftUI View](https://stackoverflow.com/questions/58286344/presenting-uiactivityviewcontroller-from-swiftui-view) – lorem ipsum May 28 '21 at 01:22
  • Thanks for the link - I ended up using the approach of setting the `popoverPresentationController` shown in this answer: https://stackoverflow.com/a/64962982/15511250 – sia May 28 '21 at 04:39
  • Check this link with ipad https://stackoverflow.com/a/71438759/14533684 – Dhaval Bera Mar 11 '22 at 13:05

0 Answers0