PHPicker - 所有选定的 UIImages 返回 nil

问题描述 投票:0回答:1

美好的一天。

我使用

PHPicker
来实现选择多张照片的功能,但在尝试处理取消选择操作时遇到了问题。

当我第二次打开照片库后取消选择其中一张预选照片时,所有图像突然变成

nil
,并且我在
Could not coerce an item to class UIImage
canLoadObject(_:)
中收到
loadObject(_:)
错误。因此,它永远不会进入我的 if 循环,并且取消选择操作永远无法完成。

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
}
swift uiimage photo phpickerviewcontroller
1个回答
0
投票
for result in results {               
        result.itemProvider.loadObject(ofClass: UIImage.self) { [weak self] object,
            error in
            if let image = object as? UIImage {
                let fileName = result.assetIdentifier
                self?.imageArray.append(ImageData.init(image: image, fileName: fileName ?? "Empty Name"))
            } else {
                let fileName = result.assetIdentifier
              //  let identifiers = results.ompactMap(\.assetIdentifier)
                let fetchResult = PHAsset.fetchAssets(withLocalIdentifiers: [fileName ?? ""], options: nil)
                                    
                if let image = fetchResult.firstObject?.image {
                    self?.imageArray.append(ImageData.init(image: image, fileName: fileName ?? "Empty Name"))
                }
            }
           //
                print("Images: \(self?.imageArray)")
                if results.count == self?.imageArray.count {
                    DispatchQueue.main.async {
                        self?.collectionView.reloadData()
                    }
                }
           // }
        }
    }

有一个解决方法,您可以使用资产标识符使用 PHAsset 获取图像

© www.soinside.com 2019 - 2024. All rights reserved.