skip to content

In SwiftUI, how do you add a ShareLink that shares a URL or a custom model, and when must you pass a SharePreview?

level: juniorimportance: should knowfreq 55%

answer

  1. a view, not a presented controller
  2. the item conforms to Transferable
  3. which item types preview themselves
  4. a title plus optional image and icon

basics

~20 s

ShareLink is a SwiftUI view that opens the system share sheet for any Transferable item. Only URL and String have initializers without a preview; a custom model must pass a SharePreview with at least a title.

solid answer

~50 s

`ShareLink` (iOS 16) turns sharing into a view: tap it and the system shows its share interface, listing the services that fit the content types the item provides. The item must conform to `Transferable`; `URL`, `String`, `Data` and SwiftUI's `Image` already do. Initializers without a `preview:` argument exist only for `URL` and `String`, because the system can build their preview itself: for a URL it shows a placeholder icon and the base URL, then fetches the page's title and icon over the network. Sharing a custom `MoodCard` therefore needs `ShareLink(item: card, preview: SharePreview(card.caption, image: thumbnail))`; leave `preview:` out and the call does not compile. A preview for a URL is optional but appears at once. `subject:` and `message:` pre-fill activities that support them, and a title string or a `label` closure replaces the default label.

code

swift · 32 lines
swift
import SwiftUI
import UniformTypeIdentifiers

extension UTType {
    static let moodCard = UTType(exportedAs: "com.example.moodboard.card")
}

struct MoodCard: Codable, Transferable {
    var caption: String
    var boardURL: URL

    static var transferRepresentation: some TransferRepresentation {
        CodableRepresentation(contentType: .moodCard)
        ProxyRepresentation(exporting: \.caption)
    }
}

struct CardToolbar: View {
    let card: MoodCard

    var body: some View {
        HStack {
            // A URL: the system builds the preview itself.
            ShareLink(item: card.boardURL)
            // A custom model: the preview argument is required.
            ShareLink(item: card,
                      subject: Text("Mood board"),
                      preview: SharePreview(card.caption,
                                            image: Image(systemName: "photo")))
        }
    }
}

go deeper

for a junior

Recall that ShareLink is a SwiftUI view taking a Transferable item, and that URL and String need no preview while your own types do.

for a middle

Explain why preview-free initializers exist only for URL and String, what SharePreview's title, image and icon are, and how subject and message pre-fill activities.

for a senior

Show that the share sheet lists services from the item's content types, so a missing Mail or AirDrop target is fixed in the Transferable conformance, often with a FileRepresentation.

for a principal

Weigh which formats a shared model exposes to other apps, since every exported representation becomes a compatibility promise the team has to keep.

## What ShareLink is **`ShareLink`** is a SwiftUI view, introduced in iOS 16, that controls a sharing presentation. When a person taps it, the system presents its share interface for the content you supplied; you never create or present a controller yourself. By default the link uses a system-standard appearance, so you only provide the content: ```swift ShareLink(item: URL(string: "https://example.com/boards/42")!) ``` Apple's documentation lists it for iOS, iPadOS, Mac Catalyst, macOS, visionOS and watchOS, and the SwiftUI interface marks it unavailable on tvOS. ## The item must be Transferable The content is described by **`Transferable`**, the Core Transferable protocol that also powers drag and drop and paste. A type conforms by declaring a static `transferRepresentation` that lists the formats it can export. Several framework types already conform: - `String` and `URL` - `Data` - SwiftUI's `Image` Your own model conforms by composing representations, for example a `CodableRepresentation` under a custom content type followed by a `ProxyRepresentation` that exports a `String`. Apple's documentation says the share interface shows **relevant sharing services based on the content types you provide**, so the representations you list decide which apps and actions appear. One item can offer several content types at once. ## When a preview is required The share sheet shows a preview of what is being shared. The system can build one automatically only for URLs and non-attributed strings, and the initializer families mirror that rule: | You share | Initializer without a preview? | What you write | |---|---|---| | A `URL` | Yes | `ShareLink(item: url)` | | A `String` | Yes | `ShareLink(item: text)` | | A custom `Transferable` model | No | `ShareLink(item: card, preview: SharePreview(...))` | | Several items | Only for `URL` or `String` elements | `ShareLink(items: cards) { SharePreview($0.caption) }` | `SharePreview` takes a **title** and, optionally, an `image:` and an `icon:`; each of those must itself be `Transferable`, and an `Image` qualifies. A title alone is enough to satisfy the compiler. Calling `ShareLink(item: card)` with a custom struct fails to type-check: the compiler reports no exact match and points at the `URL` and `String` candidates. A preview is optional for a URL but still useful. Without one, the system first shows a placeholder link icon beside the base URL while it fetches the link's metadata over the network, then updates once the title and icon arrive. If you provide a preview, it appears immediately and no fetch is needed. ## Customizing the link `ShareLink` takes a few arguments beyond the item: 1. **A title**: `ShareLink("Share board", item: url)` builds a `Label` for you. 2. **A custom label**: a trailing `label` closure, such as `Label("Share", systemImage: "square.and.arrow.up")`, replaces the default appearance. 3. **`subject:` and `message:`**: `Text` values that pre-fill share activities which support subject and message fields. 4. **`items:`**: shares a collection; for custom elements the preview becomes a closure that maps each element to its own `SharePreview`. Because it is an ordinary view, a `ShareLink` sits in a toolbar, a menu or a row like any button. ## When a share target is missing The services that appear follow the item's representations. Apple's documentation notes that some apps offer their sharing service for files but not for a wide range of data types, naming Mail, Notes, Messages and AirDrop; if one of those is missing for your model, try adding a **`FileRepresentation`** to the type's `Transferable` conformance. The same page recommends `FileRepresentation` or `DataRepresentation` when the content is not immediately available and needs an asynchronous step, such as a network request, before it can be shared, because their export closures are `async`. ## Common mistakes - Treating `ShareLink` as something you must bridge from UIKit: it is a native SwiftUI view. - Passing a `Codable` type and expecting it to share: the type must conform to `Transferable`. - Expecting a custom model to share without a preview, the way a URL does. - Registering a model's bytes under the generic `UTType.data`: Apple advises the most specific content type, so the right apps can accept it. - Assuming the share sheet looks the same for every item: the services listed depend on the content types the item offers.

  • Why pass a SharePreview when sharing a URL, where it is optional?
    Without one, the share sheet first shows a placeholder link icon and the base URL while the system fetches the page's metadata over the network, then updates when the title and icon arrive. A `SharePreview` with your own title and image appears immediately and needs no fetch, which helps when the page is slow or needs a login.
  • How do you share several mood cards from one ShareLink?
    Use the `items:` form with a preview closure: `ShareLink(items: cards) { SharePreview($0.caption) }`. The collection must be a `RandomAccessCollection` of `Transferable` elements, and for custom elements the closure builds one `SharePreview` per element, because the system cannot preview them itself.

  • ShareLink has to wrap UIActivityViewController in a representable to work.
  • Any Codable struct can be passed to ShareLink with no Transferable conformance.
  • A custom model shares with ShareLink(item:) alone, just like a URL.
  • SharePreview is mandatory for every ShareLink, URLs included.
  • Registering the model as UTType.data makes it shareable to every app.