Skip to content

Instantly share code, notes, and snippets.

@prafullakumar
Last active July 13, 2021 09:57
Show Gist options
  • Save prafullakumar/50db4e240f9c5b53e390957bf6f8098c to your computer and use it in GitHub Desktop.
Save prafullakumar/50db4e240f9c5b53e390957bf6f8098c to your computer and use it in GitHub Desktop.
struct PhotoPicker: UIViewControllerRepresentable {
let configuration: PHPickerConfiguration
@Binding var pickerResult: [UIImage]
@Binding var isPresented: Bool
func makeUIViewController(context: Context) -> PHPickerViewController {
let controller = PHPickerViewController(configuration: configuration)
controller.delegate = context.coordinator
return controller
}
func updateUIViewController(_ uiViewController: PHPickerViewController, context: Context) { }
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
/// PHPickerViewControllerDelegate => Coordinator
class Coordinator: PHPickerViewControllerDelegate {
private let parent: PhotoPicker
init(_ parent: PhotoPicker) {
self.parent = parent
}
func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
for image in results {
if image.itemProvider.canLoadObject(ofClass: UIImage.self) {
image.itemProvider.loadObject(ofClass: UIImage.self) { (newImage, error) in
if let error = error {
print(error.localizedDescription)
} else {
self.parent.pickerResult.append(newImage as! UIImage)
}
}
} else {
print("Loaded Assest is not a Image")
}
}
// dissmiss the picker
parent.isPresented = false
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment