iosswiftnsdataphpickerviewcontrolleravif

How to import AVIF image in iOS by PHPicker


I use PHPicker for user to import photos, but UIImage not support the pic of .AVIF, so I want to get the origin data of .AVIF pic, this is my code:

    func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
        picker.dismiss(animated: true)
        for image in results {
            loadImagePickerResult(image: image)
        }
    }
    
    func loadImagePickerResult(image: PHPickerResult) {
        if image.itemProvider.canLoadObject(ofClass: UIImage.self) {
            image.itemProvider.loadObject(ofClass: UIImage.self) { [weak self] newImage, error in
                guard let self = self else { return }
                if let _ = error {

                } else if let needAddImage = newImage as? UIImage {
                    let imageItem = ContentImageItem()
                    imageItem.image = needAddImage
                    self.viewModel.selectedImageList.append(imageItem)
                    DispatchQueue.main.async {
                        self.scrollImageView.reloadData()
                        self.checkConfirmState()
                    }
                }
            }
        } else if image.itemProvider.hasItemConformingToTypeIdentifier(kUTTypeImage as String) {
            image.itemProvider.loadItem(forTypeIdentifier: kUTTypeImage as String, options: nil) { [weak self] item, error in
                guard let self = self else { return }
                guard let url = item as? URL else { return }
                var imageData: Data?
                do {
                    imageData = try Data(contentsOf: url, options: [.mappedIfSafe, .alwaysMapped])
                } catch {
                }
                guard let selectedImageData = imageData else { return }
                /// selectedImageData is empty data
            }
        } else {

        }
    }

When I choose .AVIF pic, itemProvider can load the image by kUTTypeImage typeIdentifier, and success to get the local path of the pic, but when I use Data(contentsOf: ) to read the origin data, I can only get an empty data. So, is there any problem with this code?Does anyone have experience in handling this matter?

url path and empty data

I use NSData(contentsOf:) to get the origin data, but still is empty.


Solution

  • Finally, I use loadDataRepresentation with kUTTypeImage to replace .loadItem can get the image data, but I still don‘t know why the url item can only get an empty data.