Learn Courses My Dashboard

Multi image picker help needed

Help needed. Per Mikaela Caron’s recommendation on another thread, I got the following from Paul Hudson at:

https://www.hackingwithswift.com/books/ios-swiftui/importing-an-image-into-swiftui-using-phpickerviewcontroller

import PhotosUI
import SwiftUI

struct ImagePicker: UIViewControllerRepresentable {
    @Binding var image: UIImage?
    func makeUIViewController(context: Context) -> PHPickerViewController {
        var config = PHPickerConfiguration()
        config.filter = .images
        let picker = PHPickerViewController(configuration: config)
        picker.delegate = context.coordinator
        return picker
    }
    func updateUIViewController(_ uiViewController: PHPickerViewController, context: Context) {
    }
    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }
    class Coordinator: NSObject, PHPickerViewControllerDelegate {
        let parent: ImagePicker
        init(_ parent: ImagePicker) {
            self.parent = parent
        }
        func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
            picker.dismiss(animated: true)
            guard let provider = results.first?.itemProvider else { return }
            if provider.canLoadObject(ofClass: UIImage.self) {
                provider.loadObject(ofClass: UIImage.self) { image, _ in
                    self.parent.image = image as? UIImage
                }
            }
        }
    }
}

This works fine, and I can access the image variable to get a single image into the code I’m writing; in this case, building a pdf report.

Have tried many ways to get multiple images returned in an array like [image], so I can add multiple images to the pdf file in a loop. Can’t seem to get it working. Can anyone help with this? I emailed Paul, but no answer.

There is a selectionLimit property on PHPickerConfiguration. It defaults to 1 for single selection, but you can set it higher for multiple selections or to 0 for the maximum amount that the system allows.

You would obviously have to make some other changes since now you’d be working with an array instead of a single image, but I’ll leave that as an exercise for the reader.

I’m well aware of the selectionLimit, but was having trouble with setting it up. Your reply reminds me of math books: “The proof of the theorem is straightforward and left to the student as an exercise.”
Anyway, I did some more searching and found this little gem:

Thanks to this, I finally got it working.