Skip to content

Instantly share code, notes, and snippets.

@aaronlab
Last active January 27, 2021 06:21
Show Gist options
  • Save aaronlab/5ec2c3d219f494d0ac79a4b9ac6381cb to your computer and use it in GitHub Desktop.
Save aaronlab/5ec2c3d219f494d0ac79a4b9ac6381cb to your computer and use it in GitHub Desktop.
SwiftUI PHPickerView for a single photo
import SwiftUI
import PhotosUI
struct ImagePickerView: UIViewControllerRepresentable {
@Binding var image: UIImage
init(image: Binding<UIImage>) {
self._image = image
}
func makeUIViewController(context: Context) -> PHPickerViewController {
// Configuration
var configuration = PHPickerConfiguration()
configuration.selectionLimit = 1 // Set the max num of photos (0 is unlimited)
configuration.filter = .any(of: [.images])
// VC
let picker = PHPickerViewController(configuration: configuration)
picker.delegate = context.coordinator // delegate
return picker
}
func updateUIViewController(_ uiViewController: PHPickerViewController, context: Context) {}
func makeCoordinator() -> Coordinator {
Coordinator(image: self.$image)
}
}
extension ImagePickerView {
final class Coordinator: NSObject, PHPickerViewControllerDelegate {
@Binding var image: UIImage
init(image: Binding<UIImage>) {
self._image = image
}
func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
picker.dismiss(animated: true)
let itemProvider = results.first?.itemProvider
// Change image of the binded image
if let itemProvider = itemProvider,
itemProvider.canLoadObject(ofClass: UIImage.self) {
itemProvider.loadObject(ofClass: UIImage.self) { [weak self] image, error in
DispatchQueue.main.async {
guard let safeImage = image as? UIImage else { return }
self?.image = safeImage
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment