I'm working on a SwiftUI project using PHPicker. Everything currently works fine except that whenever I open the picker, will get the warning [Picker] Showing picker unavailable UI (reason: still loading) with error: (null)
Seems like the picker is not fully initialized when it gets called, and indeed it shows Loading Photos...
when launch.
Does anyone know how to solve this?
My code is like follows:
...
.toolbar {
ToolbarItem {
Button(action: {
showingImagePicker = true
}) {
Label("Add Image", systemImage: "plus")
}
}
}
.sheet(isPresented: $showingImagePicker) {
ImagePickerRepresentable(
showImagePicker: $showingImagePicker,
onCompletion: complete
)
}
this is my ImagePickerRepresentable
struct ImagePickerRepresentable: UIViewControllerRepresentable {
// MARK: - Environment Object
@Binding var showImagePicker: Bool
let onCompletion: (UIImage) -> Void
// MARK: - Coordinator Class
final class Coordinator: PHPickerViewControllerDelegate {
private let parent: ImagePickerRepresentable
init(_ parent: ImagePickerRepresentable) {
self.parent = parent
}
func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
parent.showImagePicker = false
// unpack the selected items
let itemProviders = results.map(\.itemProvider)
for itemProvider in itemProviders {
if itemProvider.canLoadObject(ofClass: UIImage.self) {
itemProvider.loadObject(ofClass: UIImage.self) { [weak self] image, error in
if let image = image as? UIImage {
self?.parent.onCompletion(image)
}
}
} else {
print("Can't load object")
}
}
}
}
func makeUIViewController(context: Context) -> PHPickerViewController {
var configuration = PHPickerConfiguration(photoLibrary: PHPhotoLibrary.shared())
configuration.filter = .images // filter only to images
configuration.selectionLimit = 3
let controller = PHPickerViewController(configuration: configuration)
controller.delegate = context.coordinator // Use Coordinator for delegation
return controller
}
func updateUIViewController(_ uiViewController: PHPickerViewController, context: Context) { }
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
}
Thanks in advance!
I tested your code and I get the same error, but it still works.
You can use my version of the picker if you want to (metadata variable is just for Firebase):
Tested with: