Search code examples
iosswiftios-app-extension

iOS custom share extension: load selected image


I'm working on a share extension for my app, to be able to use it for sharing images directly from the library. I have a view controller and layout set up, but I'm struggling with getting the selected image to show in the UIImageView inside the view controller.

For now, my getImage() is as follows:

func getImage() {
    if let inputItem = extensionContext!.inputItems.first as? NSExtensionItem {
        if let itemProvider = inputItem.attachments?.first as? NSItemProvider {
            itemProvider.loadItem(forTypeIdentifier: kUTTypeJPEG as String) { [unowned self] (imageData, error) in
                if let item = imageData as? Data {
                    self.imageView.image = UIImage(data: item)

                }
            }
        }
    }
}

...but the image is not loading. What am I doing wrong here?


Solution

  • Found the problem. Turned out I needed to do a type identifier conformance check first:

    func getImage() {
        if let inputItem = extensionContext!.inputItems.first as? NSExtensionItem {
            if let itemProvider = inputItem.attachments?.first as? NSItemProvider {
                // This line was missing
                if itemProvider.hasItemConformingToTypeIdentifier(kUTTypeJPEG as String) { 
                    itemProvider.loadItem(forTypeIdentifier: kUTTypeJPEG as String) { [unowned self] (imageData, error) in
                        if let item = imageData as? Data {
                            self.imageView.image = UIImage(data: item)
                        }
                    }
                }
            }
        }
    }