The simplest code I've implemented to share a UIImage
with better user experience:
- Import the LinkPresentation framework:
#import <LinkPresentation/LPLinkMetadata.h> // for Obj-C
import LinkPresentation // for Swift, below
- 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)
- 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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…