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

后端 未结 3 1733
傲寒
傲寒 2020-12-05 19:23

The new share sheet on iOS13 shows a preview/thumbnail of the item being shared on its top left corner.

When sharing an UIImage using an UIActivityViewController I w

3条回答
  •  遥遥无期
    2020-12-05 20:28

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

    1. Import the LinkPresentation framework:
    #import   // 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.

提交回复
热议问题