I want to automatically take an image in my application when the camera is presented. I am using SwiftUI and UIImagePickerController for the camera application.
Here is my code for the ImagePicker:
import Foundation
import SwiftUI
import UIKit
import MobileCoreServices
class ImagePickerCoordinator: NSObject, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
...
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
print("This should print if this method is called but it doesn't print")
let uiImage = info[UIImagePickerController.InfoKey.originalImage] as! UIImage
image = uiImage
isShown = false
picker.dismiss(animated: true)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
isShown = false
}
}
struct ImagePicker: UIViewControllerRepresentable {
@Binding var isShown: Bool
@Binding var image: UIImage?
@Binding var didTapCapture: Bool
@State var pic = true
func updateUIViewController(_ uiViewController: UIImagePickerController, context: UIViewControllerRepresentableContext<ImagePicker>) {
if pic{
uiViewController.takePicture() // this doesn't work and no image is found in the "func imagePickerController()" method above
}
}
func makeCoordinator() -> ImagePickerCoordinator {
return ImagePickerCoordinator(isShown: $isShown, image: $image)
}
func makeUIViewController(context: UIViewControllerRepresentableContext<ImagePicker>) -> UIImagePickerController {
let picker = UIImagePickerController()
picker.delegate = context.coordinator
picker.sourceType = .camera
picker.cameraCaptureMode = .photo
picker.allowsEditing = false
//picker.mediaTypes = [kUTTypeMovie as String]
picker.showsCameraControls = false
return picker
}
}
From some research I did myself, I think that I need to present the picker before I can take a picture, but I am not sure how to do that? Or I might be headed down the wrong track.
Any help will be appreciated.