Programmatically open ShareLink in SwiftUI

1.9k views Asked by At

Using ShareLink shows a Share button so it opens Share popup when user taps on that button.

ShareLink(item: data, subject: Text("Subject"), message: Text("Message"))

I would like to programmatically screenshot and then share on share popup. Is there any way to perform action when user taps on ShareLink button or programmatically open SharePopup like we used to do in Swift as UIActivityController ?

1

There are 1 answers

3
Ashley Mills On BEST ANSWER

You can do this by wrapping a UIActivityController in UIViewControllerRepresentable.

In this example, I'm creating a UIImage on the click of a button, and then sharing it via ImageWrapper which is required as the sheet needs item: to be Identifiable:

struct ImageWrapper: Identifiable {
    let id = UUID()
    let image: UIImage
}

struct ContentView: View {
    
    @State private var imageWrapper: ImageWrapper?
    
    var body: some View {
        Button {
            // Use your UIImage here
            self.imageWrapper = ImageWrapper(image: UIImage())
        } label: {
            Label("Share", systemImage: "square.and.arrow.up")
        }
        .sheet(item: $imageWrapper, onDismiss: {
            
        }, content: { image in
            ActivityViewController(imageWrapper: image)
        })
    }
}

struct ActivityViewController: UIViewControllerRepresentable {
    let imageWrapper: ImageWrapper
    func makeUIViewController(context: Context) -> UIActivityViewController {
        UIActivityViewController(activityItems: [imageWrapper.image], applicationActivities: nil)
    }
    
    func updateUIViewController(_ uiViewController: UIActivityViewController, context: Context) {
    }
}
struct ContentView_Previews: PreviewProvider {
    
    static var previews: some View {
        ContentView()
    }
}