如何使用 PHPicker 从图库中获取 WebP 图像

Ily*_*ter 3 xcode ios swift phpickerviewcontroller phpicker

我有一个 PHPIckerViewController,自 iOS 14 起可用。我想从画廊获取 WEBP 格式的图像。但是 PHPicker 中的项目提供程序无法加载这种格式的图像。请告诉我如何使用新的选择器在 UIButton 上选择和设置图像。

代码:

extension SixStepRegistrationViewController: PHPickerViewControllerDelegate {
func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
 
        
        let supportedRepresentations = [UTType.rawImage.identifier,
                                        UTType.tiff.identifier,
                                        UTType.bmp.identifier,
                                        UTType.png.identifier,
                                        UTType.jpeg.identifier,
                                        UTType.webP.identifier,
        ]
        for representation in supportedRepresentations {
            if results[0].itemProvider.hasRepresentationConforming(toTypeIdentifier: representation, fileOptions: .init()) {
                print(representation, " repr")
                
                    results[0].itemProvider.loadInPlaceFileRepresentation(forTypeIdentifier: representation) { (originalUrl, inPlace, error) in
                        
                            DispatchQueue.main.async {
                                print(originalUrl, "  ", inPlace)

                                self.addPhotoButton.setImage(UIImage(contentsOfFile: originalUrl!.path), for: .normal)
                            //self.dismiss(animated: true, completion: nil)
                        }
                    }
                }
       }
        
Run Code Online (Sandbox Code Playgroud)

}

谢谢

蘇哲聖*_*蘇哲聖 7

您应该使用itemProvider.loadDataRepresentation加载webp图像:

import PhotosUI
class Coordinator: PHPickerViewControllerDelegate {
  init(handler: @escaping (UIImage) -> Void) {self.handler = handler}
  
  let handler: (UIImage) -> Void
  
  func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
    for itemProvider in results.map({$0.itemProvider}) {
      if itemProvider.hasItemConformingToTypeIdentifier(UTType.webP.identifier) {
        itemProvider.loadDataRepresentation(forTypeIdentifier: UTType.webP.identifier) {data, err in
          if let data = data, let img = UIImage.init(data: data) {
            self.handler(img)
          }
        }
      } else {
        itemProvider.loadObject(ofClass: UIImage.self) {reading, err in
          if let img = reading as? UIImage {
            self.handler(img)
          }
        }
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)