Is there a way to make the PhotosUI PhotosPicker in SwiftUI source the photos directly from the Camera? I'm trying to change the PhotosPickers in my app to use the camera instead of forcing the user to select images from their image library. Is there a way to dictate the source of PhotosPicker images like you can with ImagePicker?
I did an online search and a lot of articles talked about PhotoPicker, but none of the examples had a way to make it use the camera. Should I just bite the bullet and switch everything to image picker or is there a way to make PhotoPicker use the camera?
Thanks.
CodePudding user response:
step 1 : Create a dialogue to select the option for a camera of the photo
step 2 : Create a action sheet for for image picker
struct BaseView: View {
@State var showSelection: Bool = false
@State var showPicker: Bool = false
@State var type: UIImagePickerController.SourceType = .photoLibrary
var body: some View {
Zstack {
YourView()
}
.confirmationDialog(Lables.selectImage,
isPresented: $showSelection,
titleVisibility: .hidden) {
Button(ButtonName.camera) {
showPicker = true
type = .camera
}
Button(ButtonName.photos) {
showPicker = true
type = .photoLibrary
}
}
.fullScreenCover(isPresented: $showPicker) {
ImagePickerView(sourceType: profileImageVM.pickerType) { image in
// image your image
}
}
}
}
step 3: Create Image Picker
struct ImagePickerView: UIViewControllerRepresentable {
private var sourceType: UIImagePickerController.SourceType
private let onImagePicked: (UIImage) -> Void
@Environment(\.presentationMode) private var presentationMode
public init(sourceType: UIImagePickerController.SourceType, onImagePicked: @escaping (UIImage) -> Void) {
self.sourceType = sourceType
self.onImagePicked = onImagePicked
}
public func makeUIViewController(context: Context) -> UIImagePickerController {
let picker = UIImagePickerController()
picker.sourceType = self.sourceType
picker.delegate = context.coordinator
return picker
}
public func updateUIViewController(_ uiViewController: UIImagePickerController, context: Context) {}
public func makeCoordinator() -> Coordinator {
Coordinator(
onDismiss: { self.presentationMode.wrappedValue.dismiss() },
onImagePicked: self.onImagePicked
)
}
final public class Coordinator: NSObject, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
private let onDismiss: () -> Void
private let onImagePicked: (UIImage) -> Void
init(onDismiss: @escaping () -> Void, onImagePicked: @escaping (UIImage) -> Void) {
self.onDismiss = onDismiss
self.onImagePicked = onImagePicked
}
public func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
if let image = info[.originalImage] as? UIImage {
self.onImagePicked(image)
}
self.onDismiss()
}
public func imagePickerControllerDidCancel(_: UIImagePickerController) {
self.onDismiss()
}
}
}