0

I'm implementing a share extension that sends images to a server for computation. In addition to my progress bar issues, I'm not able to use the images from Twitter app. Here is the code I'm using which is working in many other third party apps.

if let inputItem = extensionContext!.inputItems.first as? NSExtensionItem {
            if let itemProvider = inputItem.attachments?.first as? NSItemProvider {
                if itemProvider.hasItemConformingToTypeIdentifier(kUTTypeImage as String) {
                    itemProvider.loadItem(forTypeIdentifier: kUTTypeImage as String) { [unowned self] (imageData, error) in
                        let url = imageData as! URL
                        self.sendToServer(localUrl: url)
                    }
                }
            }
        }

The error I have is the following: Could not cast value of type 'NSConcreteData' (0x1a8d45700) to 'NSURL' (0x1a8d36a10) and occurs for this part of the code let url = imageData as! URL.

It seems that the item is of type image. Any idea why that is happening while it works for the other apps?

Thanks for your help.

radar
  • 500
  • 1
  • 6
  • 24

1 Answers1

0

I managed to fix that by using the following code, which takes into account different ways the photo is passed by the itemProvider.

itemProvider.loadItem(forTypeIdentifier: kUTTypeImage as String){ [unowned self] (data, error) in
                            let myImage: UIImage?
                            switch data {
                            case let image as UIImage:
                                myImage = image
                            case let data as Data:
                                myImage = UIImage(data: data)
                            case let url as URL:
                                let imageData = NSData(contentsOf: url.absoluteURL)
                                myImage = UIImage(data: imageData! as Data)
                            default:
                                //There may be other cases...
                                print("Unexpected data:", type(of: data))
                                myImage = nil
                            }
                            self.sendToServer(imageData: myImage!, imageName: myImageName)
                        }
radar
  • 500
  • 1
  • 6
  • 24