-2

I have a simple image picker (code was found somewhere on the internet):

struct ImagePicker: UIViewControllerRepresentable {
    @Binding var image: UIImage?

    func makeUIViewController(context: Context) -> PHPickerViewController {
        var config = PHPickerConfiguration()
        config.filter = .images
        let picker = PHPickerViewController(configuration: config)
        picker.delegate = context.coordinator
        return picker
    }

    func updateUIViewController(_ uiViewController: PHPickerViewController, context: Context) {

    }

    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }

    class Coordinator: NSObject, PHPickerViewControllerDelegate {
        let parent: ImagePicker

        init(_ parent: ImagePicker) {
            self.parent = parent
        }

        func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
            picker.dismiss(animated: true)

            guard let provider = results.first?.itemProvider else { return }

            if provider.canLoadObject(ofClass: UIImage.self) {
                provider.loadObject(ofClass: UIImage.self) { image, _ in
                    self.parent.image = image as? UIImage
                }
            }
        }
    }
}

The problem is that webp images won't work. They just do not load, and var image does not contain anything. Is there any way to make webp images work with my code?

I tried looking for solutions on the internet, but none of them worked for me.

misster
  • 11

1 Answers1

0

You can load the image as data and then create a UIImage from it. I guess canLoadObject should report true but for some reason doesn't so a workaround is needed:

// Check the identifier is WebP
if itemProvider.hasItemConformingToTypeIdentifier(UTType.webP.identifier) {
    // Load it as Data
    itemProvider.loadDataRepresentation(forTypeIdentifier: UTType.webP.identifier) { data, error in
        // Convert it to UIImage
        guard let data, 
              let image = UIImage(data: data) else {
            print("Failed to load WebP data or convert it to image: \(error)")
            return
        }
        
        // Use the image!
    }
}

Source: https://swiftsenpai.com/development/webp-phpickerviewcontroller/

CMash
  • 1,987
  • 22
  • 35