我一直在尝试UIDocumentPickerViewController
在 SwiftUI 中实现 a ,但运气不佳。当我在工作表中显示视图时,即使模拟器中有文件,也只有一个空白的“最近”选项卡(如下所示)。如何从 iCould drive 或“在我的 iPhone 上”选择?
文件选择器.swift
struct FilePicker: UIViewControllerRepresentable {
class Coordinator: NSObject, UIDocumentPickerDelegate, UINavigationControllerDelegate {
var parent: FilePicker
init (_ parent: FilePicker) {
self.parent = parent
}
public func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
print("chosen")
guard let documentURL = urls.first else {
return
}
if let data = try? Data(contentsOf: documentURL) {
parent.image = UIImage(data: data)
parent.presentaionMode.wrappedValue.dismiss()
}
else {
return
}
}
func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
print("cancelled")
}
}
@Binding var image: UIImage?
@Environment(\.presentationMode) var presentaionMode
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
func makeUIViewController(context: UIViewControllerRepresentableContext<FilePicker>) -> UIDocumentPickerViewController {
let pickerViewController = UIDocumentPickerViewController(forOpeningContentTypes: [.image, .jpeg, .png, .pdf], asCopy: true)
return pickerViewController
}
func updateUIViewController(_ uiViewController: UIDocumentPickerViewController, context: UIViewControllerRepresentableContext<FilePicker>) {
}
}
内容视图.swift
struct ContentView: View {
@State var image: Image?
@State var activeSheet: ActiveSheet?
@State private var inputImage: UIImage?
var body: some View {
ZStack{
//Stuff in here
}
.sheet(item: $activeSheet, onDismiss: loadImage) { item in
switch item {
case .photo:
PhotoPicker(image: $inputImage)
case .file:
FilePicker(image: $inputImage)
case .demo:
DemoPicker(image: $inputImage)
}
}
}
}
func loadImage() {
guard let inputImage = inputImage else {
print("failed input image")
return
}
image = Image(uiImage: inputImage)
showMenu = false
}
}
enum ActiveSheet: Identifiable {
case photo, file, demo
var id: Int {
hashValue
}
}