Search code examples
uikituiimageios-sharesheet

UIKit: Create a UIImage snapshot and use it as thumbnail in a shareSheet


I'm implementing snapshot sharing in iOS app, so the UIImage is created from the View and it is in the sharesheet and works fine, but I can't get to show this UIImage as a thumbnail is ShareSheet.

func actionSheet(image: UIImage) {
        let urlShare = image
        let activityVC = UIActivityViewController(activityItems: [urlShare], applicationActivities: nil)
        UIApplication.shared.windows.first?.rootViewController?.present(activityVC, animated: true, completion: nil)
    }

the UIImage is created on the fly, so there's no url for it in the app

How can I make it show it anyway?


Solution

  • got a great answer to my question from: Jake Bloom: Using Share Sheets on iOS and Android

    import Foundation
    import SwiftUI
    import LinkPresentation
    
    class ShareImage: UIActivityItemProvider {
      var image: UIImage
    
      override var item: Any {
        get {
          return self.image
        }
      }
    
      override init(placeholderItem: Any) {
        guard let image = placeholderItem as? UIImage else {
          fatalError("Couldn't create image from provided item")
        }
    
        self.image = image
        super.init(placeholderItem: placeholderItem)
      }
    
      @available(iOS 13.0, *)
      override func activityViewControllerLinkMetadata(_ activityViewController: UIActivityViewController) -> LPLinkMetadata? {
    
        let metadata = LPLinkMetadata()
        metadata.title = "Result Image"
    
        var thumbnail: NSSecureCoding = NSNull()
        if let imageData = self.image.pngData() {
          thumbnail = NSData(data: imageData)
        }
    
        metadata.imageProvider = NSItemProvider(item: thumbnail, typeIdentifier: "public.png")
    
        return metadata
      }
    
    }
    

    and then:

    func actionSheet(image: UIImage?) {
            guard let data = image else { return }
            let item = ShareImage(placeholderItem: data)
            let activityViewController = UIActivityViewController(activityItems: [item], applicationActivities: nil)
            
            UIApplication.shared.windows.first?.rootViewController?.present(activityViewController, animated: true, completion: nil)
        }