I have been trying to load an image from the photo library on a swifui app. I am running Xcode 13.2.1 and building IOS 15.2 My code is as below
@Binding var image: UIImage?
func makeUIViewController(context: Context) -> PHPickerViewController {
var config = PHPickerConfiguration()
config.filter = .images
config.selectionLimit = 1
config.preferredAssetRepresentationMode = .compatible
let controller = PHPickerViewController(configuration: config)
controller.delegate = context.coordinator
return controller
}
func updateUIViewController(_ uiViewController: PHPickerViewController, context: Context) { }
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
// Use a Coordinator to act as your PHPickerViewControllerDelegate
class Coordinator: NSObject, PHPickerViewControllerDelegate {
private let parent: PhotoPicker
init(_ parent: PhotoPicker) {
self.parent = parent
}
func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
picker.dismiss(animated: true)
print(results)
guard !results.isEmpty else {
return
}
guard let itemProvider = results.first?.itemProvider else { return }
print("Invoking getPhoto")
self.getPhoto2(from: itemProvider)
//parent.didFinishPicking(!results.isEmpty)
}
private func getPhoto2(from itemProvider: NSItemProvider) {
print("getPhoto")
if itemProvider.canLoadObject(ofClass: UIImage.self) {
itemProvider.loadObject(ofClass: UIImage.self) { image, error in
self.parent.image = image as? UIImage
print("Loaded Image \(error)")
}
}
}
}
}
On the console I see the following error
022-01-27 00:40:01.485085-0500 Vescense[3174:884964] [Picker] Showing picker unavailable UI (reason: still loading) with error: (null)
Further when I print the result I see
[PhotosUI.PHPickerResult(itemProvider: <PUPhotosFileProviderItemProvider: 0x2818fc980> {types = (
"public.jpeg",
"public.heic"
)}, assetIdentifier: nil)]
It doesn't appear like the error on loadObject has a value. And it's suspicious that assetIdentifier is nil.
Any thoughts on what I might be missing here would be most helpful.