Handling WebP Images When Using PHPickerViewController

Be cautious when using PHPickerViewController

Lee Kah Seng

--

This article is originally published at swiftsenpai.com

This week, I worked on a feature that required integration with the PHPickerViewController. Everything went well until I noticed that some of the selected images failed to convert into UIImage in the picker(_:didFinishPicking:) delegate method.

Upon investigation, I discovered that the issue arose because some of the images were in WebP format, and the way to handle image results recommended by Apple did not work for WebP images.

Fortunately, resolving the issue is quite straightforward. All we need to do is load the WebP image as data and convert it to a UIImage.

Let me show you.

Why Does It Fail?

In this WWDC video, Apple recommends using the following code to handle images from a PHPickerViewController:

if itemProvider.canLoadObject(ofClass: UIImage.self) {

// Handle UIImage type
itemProvider.loadObject(ofClass: UIImage.self) { image, error in

guard let resultImage = image as? UIImage else {
return
}

// Do something with `resultImage`
}
}

The issue arises because the loadObject(ofClass:) method does not support the WebP image format, resulting in the canLoadObject(ofClass:) method returning false.

To resolve this problem, we will have to rely on another way for loading WebP images. Let’s take a look.

How to Handle WebP Images When Using PHPickerViewController?

The method we are looking for is loadDataRepresentation(forTypeIdentifier:completionHandler:). This method allows us to convert the given WebP image into a generic data object.

Once we have the data object, it becomes straightforward to convert it into UIImage.

// Get the first item provider from the results
guard let itemProvider = results.first?.itemProvider else {
return
}

// Ensure that image format is WebP
if itemProvider.hasItemConformingToTypeIdentifier(UTType.webP.identifier) {

// Convert WebP…

--

--

Lee Kah Seng

Support me by becoming a Medium member: https://leekahseng.medium.com/membership ⦿ 🇲🇾 Creator of https://swiftsenpai.com ⦿ iOS developer since 2011