UIImage must conform to _ObjectiveCBridgeable in PHPickerViewControllerDelegate callback
Asked Answered
K

3

7

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

Kaiserism answered 17/2, 2021 at 11:14 Comment(1)
I am seeing this error too. Did you ever find a solution?Peay
L
6

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

if let typeCastedImage = image as? UIImage {
  self.parent.didCapture(typeCastedImage)
}
Libratory answered 13/6, 2021 at 17:37 Comment(1)
The error in question is on the lineresult.itemProvider.loadObject(ofClass: UIImage.self).Peay
O
1

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.

Ohl answered 11/12, 2022 at 8:51 Comment(0)
M
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
        ...
    }
Misconstruction answered 28/2, 2023 at 0:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.