Last active
November 17, 2022 23:31
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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