0

Here's the code I have:

private struct ShareButton: UIViewRepresentable {
    func makeUIView(context: Context) -> UIButton {
        let activityViewController = UIActivityViewController(activityItems: [URL(string: "https://www.apple.com/")!], applicationActivities: nil)
        let action = UIAction(title: "Share") { _ in UIApplication.shared.windows.first(where: { $0.isKeyWindow })?.rootViewController?.present(activityViewController, animated: false) }
        let button = UIButton(primaryAction: action)
        activityViewController.popoverPresentationController?.sourceView = button
        return button
    }
    func updateUIView(_ uiView: UIButton, context: Context) { }
}

Basically it's creating a UIButton with a UIAction, inside which there's a UIActivityViewController that set sourceView for the share menu to be the UIButton.

Here's a demo of the issue:

The UIButton is created when the SwiftUI view is created, and set as the sourceView. My guess is that the issue occur because the UIButton is somehow destroyed and recreated due to some SwiftUI mechanism? I can be entirely wrong though. Anyway to solve this?

Or any other way to do share button in a SwiftUI Catalyst Mac app?

Tom
  • 118
  • 1
  • 6

2 Answers2

0

"Or any other way to do share button in a SwiftUI Catalyst Mac app?"

You could try this approach, using the extension from: How to get rid of message " 'windows' was deprecated in iOS 15.0: Use UIWindowScene.windows on a relevant window scene instead" with AdMob banner?

public extension UIApplication {
    func currentUIWindow() -> UIWindow? {
        let connectedScenes = UIApplication.shared.connectedScenes
            .filter({
                $0.activationState == .foregroundActive})
            .compactMap({$0 as? UIWindowScene})

        let window = connectedScenes.first?
            .windows
            .first { $0.isKeyWindow }

        return window

    }
}

struct ContentView: View {
    let holaTxt = "Hola  "
    
    var body: some View {
        Button(action: {
            let AV = UIActivityViewController(activityItems: [holaTxt], applicationActivities: nil)
            UIApplication.shared.currentUIWindow()?.rootViewController?.present(AV, animated: true, completion: nil)
        }) {
            Text("Share")
        }
    }
}
0

Found an elegant solution for creating a share button in a SwiftUI Catalyst Mac app (in fact, all SwiftUI app), see https://github.com/SwiftUI-Plus/ActivityView

Tom
  • 118
  • 1
  • 6
  • When linking to your own site or content (or content that you are affiliated with), you must [disclose your affiliation in the answer](https://stackoverflow.com/help/promotion) in order for it not to be considered spam. Having the same text in your username as the URL or mentioning it in your profile is not considered sufficient disclosure under Stack Exchange policy. – Tyler2P Nov 15 '21 at 18:50
  • @Tyler2P wdym? that's not my content – Tom Nov 15 '21 at 19:28