user15147284
user15147284

Reputation:

UIImage must conform to _ObjectiveCBridgeable in PHPickerViewControllerDelegate callback

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

Upvotes: 8

Views: 2280

Answers (3)

Alexandra Smau
Alexandra Smau

Reputation: 51

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
        ...
    }

Upvotes: 1

Vadim Popov
Vadim Popov

Reputation: 91

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.

Upvotes: 1

PK-V
PK-V

Reputation: 214

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

if let typeCastedImage = image as? UIImage {
  self.parent.didCapture(typeCastedImage)
}

Upvotes: 7

Related Questions