Using Xcode 14.0 I'm trying to open a file with SwiftUI as interface:
import SwiftUI
struct ContentView: View {
var body: some View {
VStack {
Spacer()
FilePickerView()
Spacer()
}
.padding()
}
}
Where the FilePickerView should just print the file url:
import SwiftUI
import UniformTypeIdentifiers
struct FilePickerView: View {
@State private var selectedFile: URL?
var body: some View {
VStack {
Button("Select File") {
let types = [UTType.data]
let documentPicker = UIDocumentPickerViewController(forOpeningContentTypes: types)
let delegate = FilePickerDelegate(selectedFile: $selectedFile)
documentPicker.delegate = delegate
// Find the first window scene
guard let windowScene = UIApplication.shared.connectedScenes.first(where: { $0.activationState == .foregroundActive }) as? UIWindowScene else {
return
}
// Find the key window in the scene
guard let keyWindow = windowScene.windows.first(where: { $0.isKeyWindow }) else {
return
}
keyWindow.rootViewController?.present(documentPicker, animated: true, completion: nil)
}
}
}
}
class FilePickerDelegate: NSObject, UIDocumentPickerDelegate {
@Binding var selectedFile: URL?
init(selectedFile: Binding<URL?>) {
_selectedFile = selectedFile
}
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
for url in urls {
print(url)
}
}
func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
controller.dismiss(animated: true, completion: nil)
}
}
After selecting a file, on real hardware (iOS 16) and within the simulator (iOS 16) this error occurs: (The App is called OpenFile)
2023-03-19 13:24:34.897379+0100 OpenFile[21887:809433] [AXRuntimeCommon] Unknown client: OpenFile 2023-03-19 13:24:37.962187+0100 OpenFile[21887:809278] [DocumentManager] The view service did terminate with error: Error Domain=_UIViewServiceErrorDomain Code=1 "(null)" UserInfo={Terminated=disconnect method}
What needs to be set to make this simple task possible?