Skip to content

Instantly share code, notes, and snippets.

@andresr-dev
Last active November 17, 2022 23:31
Show Gist options
  • Select an option

  • Save andresr-dev/94c29f6330014f4264b63b545074c8ac to your computer and use it in GitHub Desktop.

Select an option

Save andresr-dev/94c29f6330014f4264b63b545074c8ac to your computer and use it in GitHub Desktop.
This is how you can pick an Image from your photo library in SwiftUI
import PhotosUI
import SwiftUI
struct ImagePicker: UIViewControllerRepresentable {
@Binding var image: UIImage?
class Coordinator: NSObject, PHPickerViewControllerDelegate {
let parent: ImagePicker
init(_ parent: ImagePicker) {
self.parent = parent
}
func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
picker.dismiss(animated: true)
guard let provider = results.first?.itemProvider else { return }
if provider.canLoadObject(ofClass: UIImage.self) {
provider.loadObject(ofClass: UIImage.self) { object, _ in
DispatchQueue.main.async {
self.parent.image = object as? UIImage
}
}
}
}
}
func makeUIViewController(context: Context) -> PHPickerViewController {
var config = PHPickerConfiguration()
config.filter = .images
let picker = PHPickerViewController(configuration: config)
picker.delegate = context.coordinator
return picker
}
func updateUIViewController(_ uiViewController: PHPickerViewController, context: Context) {
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment