Skip to content

Instantly share code, notes, and snippets.

@thomas-sivilay
Last active September 14, 2020 16:26
Show Gist options
  • Save thomas-sivilay/f1a46809859f59c342cb3973d8598559 to your computer and use it in GitHub Desktop.
Save thomas-sivilay/f1a46809859f59c342cb3973d8598559 to your computer and use it in GitHub Desktop.
SwiftUI with UIImagePickerController
final class UserData: ObservableObject {
@Published var image: UIImage? = nil
}
struct ContentView: View {
@EnvironmentObject var userData: UserData
@State var pickerIsActive: Bool = false
var body: some View {
NavigationView {
if userData.image != nil {
Image(uiImage: userData.image!)
}
Button(action: {
self.pickerIsActive = true
}) {
Text(“Import image”)
}
.sheet(isPresented: $pickerIsActive) {
ImagePicker().environmentObject(self.userData)
}
}
}
}
struct ImagePickerViewController: UIViewControllerRepresentable {
@Binding var presentationMode: PresentationMode
@Binding var image: UIImage?
func makeUIViewController(context: UIViewControllerRepresentableContext<ImagePickerViewController>) -> UIImagePickerController {
let imagePicker = UIImagePickerController()
imagePicker.sourceType = UIImagePickerController.SourceType.photoLibrary
imagePicker.allowsEditing = false
imagePicker.delegate = context.coordinator
return imagePicker
}
func updateUIViewController(_ uiViewController: UIImagePickerController, context: UIViewControllerRepresentableContext<ImagePickerViewController>) {
}
func makeCoordinator() -> Coordinator {
return Coordinator(self)
}
class Coordinator: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var parent: ImagePickerViewController
init(_ parent: ImagePickerViewController) {
self.parent = parent
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
let imagePicked = info[.originalImage] as! UIImage
parent.image = imagePicked
parent.presentationMode.dismiss()
picker.dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
parent.presentationMode.dismiss()
picker.dismiss(animated: true, completion: nil)
}
}
}
struct ImagePicker : View {
@EnvironmentObject var userData: UserData
@Environment(\.presentationMode) var presentationMode
var body: some View {
ImagePickerViewController(image: $userData.image, presentationMode: presentationMode)
}
}
@jkusachi
Copy link

This is great! thanks for this!!!

if anyone else comes across this, PresentationButton has been renamed to PresentationLink. Mine looks like this

PresentationLink(destination: ImagePicker().environmentObject(userData), label: {
   Text("Import Photo")
})

@thomas-sivilay
Copy link
Author

Thank you.
With the beta4 it needs even more update, I'll take some time this week end to update this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment