6

I have reviewed the WWDC2020 video explaining how to adopt the new PHPickerViewController API. I have also seen several blogs showing exactly the following code.

func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
    if let result = results.first, result.itemProvider.canLoadObject(ofClass: UIImage.self) {
        result.itemProvider.loadObject(ofClass: UIImage.self) { (image, error) in
            DispatchQueue.main.async {
                self.parent.didCapture(image)
            }
        }
    } else {
        parent.didCapture(nil)
    }
}

However, this fails for me and the error is quite bizarre.

UIImage must confirm to _ObjectiveCBridgable

I will include a screenshot because it is quite unbelievable

enter image description here

Hardware: M1 chipset

IDE: Xcode 12.4

3 Answers3

5

Type cast image as UIImage before using, that should solve the issue.

if let typeCastedImage = image as? UIImage {
  self.parent.didCapture(typeCastedImage)
}
PK-V
  • 194
  • 1
  • 9
  • 3
    The error in question is on the line`result.itemProvider.loadObject(ofClass: UIImage.self)`. – Giles May 20 '22 at 09:41
0

It depends on how you work with the values inside the function body. There are two implementations for the loadObject() function. One of them can actually accept UIImage.self. In my case, the following code works:

func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
    if let itemProvider = results.first?.itemProvider, itemProvider.canLoadObject(ofClass: UIImage.self) {
        itemProvider.loadObject(ofClass: UIImage.self) { image, error in
            if let image = image as? UIImage {
                DispatchQueue.main.async {
                    self.imageViewField.image = image
                }
            }
        }
    }
}

It is necessary to make a check for conformance to the type of UIImage.

Vadim Popov
  • 71
  • 1
  • 6
0

The issue is that there is another function with the same name that requires the class to conform to _ObjectiveCBridgeable

To force the compiler to choose the right function, you can define the type to be NSItemProviderReading.Type:

    let type: NSItemProviderReading.Type = UIImage.self

    result.itemProvider.loadObject(ofClass: type) { image, error in
        ...
    }