Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
struct ImagePicker: UIViewControllerRepresentable {
typealias UIViewControllerType = UIImagePickerController
typealias SourceType = UIImagePickerController.SourceType
let sourceType: SourceType
let completionHandler: (UIImage?) -> Void
func makeUIViewController(context: Context) -> UIImagePickerController {
let viewController = UIImagePickerController()
viewController.delegate = context.coordinator
viewController.sourceType = sourceType
return viewController
}
func updateUIViewController(_ uiViewController: UIImagePickerController, context: Context) {}
func makeCoordinator() -> Coordinator {
return Coordinator(completionHandler: completionHandler)
}
final class Coordinator: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
let completionHandler: (UIImage?) -> Void
init(completionHandler: @escaping (UIImage?) -> Void) {
self.completionHandler = completionHandler
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
let image: UIImage? = {
if let image = info[.editedImage] as? UIImage {
return image
}
return info[.originalImage] as? UIImage
}()
completionHandler(image)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
completionHandler(nil)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment