swiftui

How to use a system Image, ie Image(systemName:), as the image in a SharePreview


I'm curious, is there a way to use a systemImage in a SharePreview struct? In my attempts, there's no problem compiling things, but when running my app, the preview's icon is blank.

Here's some code that illustrates this:

struct SystemImageInSharePreview: View {
    var body: some View {
        let uiImage = UIImage(named: "sample")!    // from asset catalog
        let image = Image("sample")
        let systemImage = Image(systemName: "photo")
        
        VStack {
            ShareLink(
                item: image,
                preview: SharePreview("<- Preview Image Here", icon: systemImage)
//                preview: SharePreview("<- Preview Image Here", icon: image)
//                preview: SharePreview("<- Preview Image Here", icon: uiImage)
            )
            Text("Hello World!")
        }
    }
}

Here's how it looks when run as above:

Share Sheet without Preview

So even though there are no compile or console errors, the share sheet doesn't show the icon parameter when I pass it a systemImage. However, switching to either commented-out alternative gives a preview the way I expect.

I find no indication in the docs for SharePreview that would indicate any restrictions on the type of Image passed in. Is there something that explains what is going on and how to overcome this problem?


Solution

  • The issue is that SharePreview doesn't display system images (like Image(systemName: "photo")) correctly in the share sheet. It works with a UIImage or an Image made from a UIImage.

    To fix this, convert the system image to a UIImage first:

    struct SystemImageInSharePreview: View {
        var body: some View {
            let uiImage = UIImage(named: "sample")!    // from asset catalog
            let systemUIImage = UIImage(systemName: "photo")!  // Convert system image to UIImage
            
            VStack {
                ShareLink(
                    item: uiImage,
                    preview: SharePreview("<- Preview Image Here", icon: Image(uiImage: systemUIImage))
                )
                Text("Hello World!")
            }
        }
    }