Hello everybody,
in this post, I wrote about sharing and exporting files using FileExporter or UIActivityViewController because I thought there was no native SwiftUI version of the UIActivityViewController. Turns out, there is. It is called ShareLink, and it is pretty easy to use. It works like its UIKit equivalent without the need for additional steps. So how do we use it? Easy. If you want to share a file, you have to create it first, like I described in the other post, and then you can use it just like this:
ShareLink(item: fileUrl)
Or maybe you want to share a link to your website? Then, specify a web URL.
ShareLink("Share my blog", item: URL(string: "https://www.dantersec.com")!)
Which results in this :
The default text is “Share…” but it can be changed with the first parameter. And if you want another icon, you can define a label in a trailing closure:
ShareLink(item: URL(string: "https://www.dantersec.com")!) {
Label("Share", image: "BlogIcon")
}
You can share everything using a ShareLink that conforms to the Transferable protocol (like URLs). If you want to show a specific preview in the share interface, you can also do that by using the preview argument and passing a SharePreview() to it.
ShareLink(item: photo,
preview: SharePreview(
photo.caption,
image: photo.image))
So that’s it: an easy method to share things with SwiftUI without the need for a UIViewControllerRepresentable.