// The system's document picker, raised from code and awaited: a book's Add // file. UIKit's, never a second SwiftUI // `.fileImporter`: the deck already holds one (`DoorFiles`), and with two in // one tree SwiftUI hands the file to the wrong one (a book's Add file came // back as a new book through the deck's door). import SwiftUI import UniformTypeIdentifiers #if os(iOS) import UIKit #elseif os(macOS) import AppKit #endif @MainActor enum SystemFilePicker { /// The one file chosen of these types, read in place: empty when the /// person cancelled, nil when no picker could be shown. static func pick(_ types: [UTType]) async -> [URL]? { #if os(iOS) guard let top = SystemShareSheet.topViewController() else { return nil } let delegate = PickerDelegate() let picker = UIDocumentPickerViewController(forOpeningContentTypes: types, asCopy: false) picker.allowsMultipleSelection = false picker.delegate = delegate let urls = await withCheckedContinuation { continuation in delegate.continuation = continuation top.present(picker, animated: true) } withExtendedLifetime(delegate) {} return urls #elseif os(macOS) let panel = NSOpenPanel() panel.allowedContentTypes = types panel.allowsMultipleSelection = false return await panel.begin() == .OK ? panel.urls : [] #else return nil #endif } } #if os(iOS) @MainActor private final class PickerDelegate: NSObject, UIDocumentPickerDelegate { var continuation: CheckedContinuation<[URL], Never>? func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) { continuation?.resume(returning: urls) continuation = nil } func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) { continuation?.resume(returning: []) continuation = nil } } #endif