iOS Share Extension - handle screenshot data

1k views Asked by At

I am trying to receive screenshot data from my Share Extension. I am running iOS 15.5.

override func didSelectPost() {
   if let extensionItems = self.extensionContext?.inputItems as? [NSExtensionItem]  {
      let attachments     = extensionItems.first?.attachments ?? []
      let imageType       = UTType.image.identifier
      
      for provider in attachments {
         if provider.hasItemConformingToTypeIdentifier(imageType) {
            print("It is an image")

            // this seems only to handle media from photos
            provider.loadFileRepresentation(forTypeIdentifier: imageType) { (unsafeFileUrl, error) in
               print("We have the image")
            }
         }
      }
   }
}

Observed behaviour

  • When sharing a photo from the Photos App, the didSelectPost() method works as expected.
  • When capturing an image from the Share button, I can see the print("It is an image"), however I cannot access the actual image data.

What I have tried

  • I have tried to access the provider's content using loadItem and loadDataRepresentation, neither trigger a print statement.
  • Other StackOverflow question suggest using

Questions that have not resolved my issue

Expected behaviour

  • I get the Screen Shot image data which I can save to disc.

Queries

  • Why can I not access the Screen Shot data?
  • How do I access the screen shot data?
2

There are 2 answers

4
Buyin Brian On

I had the same issue. The data from the screenshot is actually a UIImage, so this worked for me:


                         //sometimes the item is a UIImage (i.e., screenshots)
                         itemProvider.loadItem(forTypeIdentifier: UTType.image.identifier) { item, error in
                             if let image = item as? UIImage {
                                 DispatchQueue.main.async { [weak self] in
                                     guard let self = self else { return }
                                     self.imageView.image =   image
                                 }
                                 return
                             }

                         }
2
Buyin Brian On

Did you add the activation rules to the info.plist of the share sheet:

        <dict>
            <key>NSExtensionActivationRule</key>
            <dict>
                <key>NSExtensionActivationSupportsImageWithMaxCount</key>
                <integer>1</integer>
                <key>NSExtensionActivationSupportsText</key>
                <true/>
            </dict>
        </dict>