preselectedAssetIdentifiers
If you have chosen PHPicker while creating a gallery picker in an application you created with SwiftUI, and you want to prevent this picker from selecting the selected photos over and over again, you can apply the following method.
The feature that will prevent the user from selecting the same photo twice is "preselectedAssetIdentifiers"
import Foundation
import PhotosUI
import SwiftUI
struct GalleryPicker: UIViewControllerRepresentable {
func makeCoordinator() -> Coordinator {
return GalleryPicker.Coordinator(parent: self)
}
@Binding var images: [UIImage]
@Binding var picker: Bool
@Binding var preSelected: [String]
func makeUIViewController(context: Context) -> PHPickerViewController {
var configuration = PHPickerConfiguration(photoLibrary: .shared())
configuration.preselectedAssetIdentifiers = preSelected
configuration.filter = .images
configuration.selection = .ordered
configuration.selectionLimit = 0
let picker = PHPickerViewController(configuration: configuration)
picker.delegate = context.coordinator.self
return picker
}
func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) {
}
class Coordinator: NSObject, PHPickerViewControllerDelegate {
var parent: GalleryPicker
init(parent: GalleryPicker) {
self.parent = parent
}
func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
parent.picker.toggle()
for result in results {
let provider = result.itemProvider
let assetIdentifier = result.assetIdentifier ?? ""
print("asset --> \(assetIdentifier)")
if provider.canLoadObject(ofClass: UIImage.self) {
provider.loadObject(ofClass: UIImage.self) { image, _ in
DispatchQueue.main.async {
self.parent.preSelected.append(assetIdentifier)
self.parent.images.append(image as! UIImage)
}
}
}
}
}
}
}
screenshot
info[UIImagePickerControllerReferenceURL]
should be unique for each images so you can keep that to check if it is already picked – Africah