我正在使用 PHPicker 开发一个 SwiftUI 项目。目前一切正常,除了每当我打开选择器时,都会收到警告[Picker] Showing picker unavailable UI (reason: still loading) with error: (null)
似乎选择器在被调用时没有完全初始化,并且确实Loading Photos...
在启动时显示。
有谁知道如何解决这个问题?
我的代码如下:
...
.toolbar {
ToolbarItem {
Button(action: {
showingImagePicker = true
}) {
Label("Add Image", systemImage: "plus")
}
}
}
.sheet(isPresented: $showingImagePicker) {
ImagePickerRepresentable(
showImagePicker: $showingImagePicker,
onCompletion: complete
)
}
这是我的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)
}
}
提前致谢!