Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically open ShareLink in SwiftUI

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 ?

like image 491
HarshIT Avatar asked Apr 06 '26 07:04

HarshIT


1 Answers

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()
    }
}
like image 155
Ashley Mills Avatar answered Apr 09 '26 03:04

Ashley Mills