美好的一天。
我使用
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
}
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 获取图像