iOS13 share sheet: how to set preview thumbnail when sharing UIImage

The simplest code I’ve implemented to share a UIImage with better user experience:

  1. Import the LinkPresentation framework:
#import <LinkPresentation/LPLinkMetadata.h>  // for Obj-C

import LinkPresentation  // for Swift, below
  1. Present the UIActivityViewController in the UIViewController, with [image, self]:
let image = UIImage(named: "YourImage")!
let share = UIActivityViewController(activityItems: [image, self], applicationActivities: nil)
present(share, animated: true, completion: nil)
  1. Make the UIViewController conform to UIActivityItemSource:
func activityViewControllerPlaceholderItem(_ activityViewController: UIActivityViewController) -> Any {
    return ""
}

func activityViewController(_ activityViewController: UIActivityViewController, itemForActivityType activityType: UIActivity.ActivityType?) -> Any? {
    return nil
}

func activityViewControllerLinkMetadata(_ activityViewController: UIActivityViewController) -> LPLinkMetadata? {
    let image = UIImage(named: "YourImage")!
    let imageProvider = NSItemProvider(object: image)
    let metadata = LPLinkMetadata()
    metadata.imageProvider = imageProvider
    return metadata
}

Because UIImage has already conformed to NSItemProviderWriting, just serve it for NSItemProvider.

Since it’s sharing a UIImage, any URL shouldn’t be expected. Otherwise user may get URL sharing, rather than image sharing experience.

To accelerate the share sheet preview, feed LPLinkMetadata object with existing resources. No need to fetch it online again. Check the WWDC19 Tech Talks video What’s New in Sharing for more details.

Leave a Comment