I’m trying to pick an array of images from the photos library to attach to a PDF file. I can attach text and images OK, for images in my Assets.xcassets. To get the image array, I used the WWDC2021 presentation on the new photo picker. Here’s the boilerplate from the presentation:
class ViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
var itemProviders: [NSItemProvider] = []
var iterator: IndexingIterator<[NSItemProvider]>?
// MARK: Present Picker
@IBAction func presentPicker(_ sender: Any) {
var configuration = PHPickerConfiguration()
configuration.filter = .images
configuration.selectionLimit = 0
let picker = PHPickerViewController(configuration: configuration)
picker.delegate = self
present(picker, animated: true)
}
func displayNextImage() {
if let itemProvider = iterator?.next(), itemProvider.canLoadObject(ofClass: UIImage.self) {
let previousImage = imageView.image
itemProvider.loadObject(ofClass: UIImage.self) { [weak self] image, error in
DispatchQueue.main.async {
guard let self = self, let image = image as? UIImage, self.imageView.image ==
previousImage else { return }
self.imageView.image = image
}
}
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
displayNextImage()
}
}
extension ViewController: PHPickerViewControllerDelegate {
func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
dismiss(animated: true)
itemProviders = results.map(\.itemProvider)
iterator = itemProviders.makeIterator()
displayNextImage()
}
}
I’m trying to call with button from ‘ReportView’, which includes:
@State var vc = ViewController()
The button code:
Button {
vc.presentPicker(self)
} label: {
Image(systemName: "ladybug")
}
When I press the button I get the following:
“Attempt to present <PHPickerViewController: 0x7fd5b3208070> on <SatLinks.ViewController: 0x7fd5b3380d80> (from <SatLinks.ViewController: 0x7fd5b3380d80>) whose view is not in the window hierarchy.”
I don’t have a storyboard and trying to avoid. Is there a missing connection of some type? plist problem? I suspect there is a simple solution, but couldn’t find one on line.