The iPhone, for years, has given users the ability to share items with other users. This capability has been around since iOS 6 in the form of UIActivityViewController that allows you to share items like photos, text, websites, files with other services.
Apple created a new way to share items with the introduction of ShareLink. This was first available in iOS 16 and is part of SwiftUI. Apple has conveniently built this into a View that is simple to use.
let shareURL = URL(string: "https://www.devfright.com")!
.
.
.
ShareLink(item: shareURL) {
Label("Share URL", systemImage: "link")
}
If we put this in a View we will have a link with the text “Share URL”. If we tap on that link then the share sheet will open with the option of sharing the address of this website with someone, or with the option to open it in other apps. You can replace shareURL with shareText and pass in a String and it can also pass a string along.
Sharing an Image with ShareLink
We just shared a URL, and I mentioned that you can pass in a String as well. Lets take a look at sharing an image.
let shareImage = Image(systemName: "bolt.fill")
.
.
.
ShareLink(item: shareImageRenderer(), preview: SharePreview("Bolt Icon", image: shareImage)) {
Label("Share Image", systemImage: "photo")
}
The code above shows how you can add a SharePreview and an image. This is what appears in the share sheet when toy tap on the ShareLink. Before we run this version we also need to implement shareImageRenderer().
func shareImageRenderer() -> URL {
let renderer = ImageRenderer(content: shareImage)
let tempURL = FileManager.default.temporaryDirectory.appendingPathComponent("bolt.png")
if let data = renderer.uiImage?.pngData() {
try? data.write(to: tempURL)
}
return tempURL
}
Line 2 is used to convert an image into a UIImage which is platform-native. ImageRenderer came along in iOS 16.
We then get a temporary directory on line 3. A temporaryDirectory is good to use for throw-away files.
With the rendered and uiImage property, we call the pndData() method and we write the file to the tempURL that was created. We then return this URL.
This gives our ShareLink in the view the directory to the image that is about to be shared.
When you hit the link, you’ll now see a preview of the image and the png file will be in the temp directory and available to share via text, WhatsApp, or any other app that is available and can accept the image.
For this example we needed to convert the Image in the view into the .png because we cannot share a View with ShareLink.
Transferable Protocol
The ShareLink view requires that anything shared conforms to the Transferable protocol. The Transferable protocol tells the system how to serialise data for sharing. In some cases, such as for URL and String, classes do not conform to Transferable, but still work. Apple handles these behind the scenes.
Leave a Reply
You must be logged in to post a comment.