SwiftUI:
«`swift
import SwiftUI
struct DocumentPickerView: View {
@State private var documentURL: URL?
var body: some View {
VStack {
if let documentURL = documentURL {
Text(«Selected File: (documentURL.lastPathComponent)»)
} else {
Button(«Open Document») {
let documentPicker = UIDocumentPickerViewController(forOpeningContentTypes: [.text, .pdf])
documentPicker.delegate = self
present(documentPicker, animated: true)
}
}
}
}
}
extension DocumentPickerView: UIDocumentPickerDelegate {
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
guard let documentURL = urls.first else { return }
self.documentURL = documentURL
}
func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
// Handle cancellation
}
}
«`
UIKit:
«`swift
import UIKit
class DocumentPickerViewController: UIViewController, UIDocumentPickerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let documentPicker = UIDocumentPickerViewController(documentTypes: [«public.text», «public.pdf»], in: .import)
documentPicker.delegate = self
self.present(documentPicker, animated: true, completion: nil)
}
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
guard let documentURL = urls.first else { return }
// Handle selected document
}
func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
// Handle cancellation
}
}
«`