0

Good day.

I'm using PHPicker in order to implement the use of selecting multiple photos and I've encountered an issue when trying to handle the deselecting action.

When I deselect one of the pre-selected photos from the photo library after opening it up for the second time, all of the images suddenly become nil and I get a Could not coerce an item to class UIImage error in canLoadObject(_:) and loadObject(_:). Because of this, it never enters my if loop and the deselection action can never be done.

func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
    let identifiers = results.compactMap(\.assetIdentifier)
    self.parent.imageIdentifierArray = identifiers
        
    // unpack the selected items
    for image in results {
        if image.itemProvider.canLoadObject(ofClass: UIImage.self) {
            image.itemProvider.loadObject(ofClass: UIImage.self) { [weak self] newImage, error in
                if let error = error {
                    print("Can't load image \(error.localizedDescription)") // GETTING THIS ERROR WHEN I OPEN THE PHOTO LIBRARY FOR THE SECOND TIME AND DESELECT A PHOTO
                } else if let image = newImage as? UIImage {
                    // Add new image and pass it back to the main view
                    DispatchQueue.main.async {
                        if let index = self!.parent.selectedPhotos.firstIndex(where: { $0.pngData() == image.pngData() }) {
                            self!.parent.selectedPhotos.remove(at: index)
                        } else {
                            self!.parent.selectedPhotos.append(image)
                        }
                    }
                }
            }
        } else {
            print("Error loading asset")
        }
    }
    // close the modal view
    parent.isPresented = false
}
lex
  • 113
  • 8

0 Answers0