With the introduction of UIDocumentPicker in iOS, managing files and documents in your Swift applications has become streamlined. UIDocumentPicker allows users to select documents from different sources like iCloud, Google Drive, Dropbox, and other document providers. Here’s how to implement it in your iOS app.
To use UIDocumentPicker for picking documents, first, ensure that you have imported the necessary module:
import UIKit
import MobileCoreServices
class ViewController: UIViewController, UIDocumentPickerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Create a button to initiate document picking
let pickDocumentButton = UIButton(type: .system)
pickDocumentButton.setTitle("Pick Document", for: .normal)
pickDocumentButton.addTarget(self, action: #selector(pickDocument), for: .touchUpInside)
view.addSubview(pickDocumentButton)
pickDocumentButton.center = view.center
}
@objc func pickDocument() {
let documentPicker = UIDocumentPickerViewController(documentTypes: [String(kUTTypePDF)], in: .import)
documentPicker.delegate = self
documentPicker.modalPresentationStyle = .formSheet
present(documentPicker, animated: true, completion: nil)
}
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
guard let selectedFileURL = urls.first else { return }
print("Picked document at: \(selectedFileURL)")
// Implement your document handling logic here
}
func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
print("Document picker was cancelled")
}
}
This example demonstrates how to create a simple document picker in your app. The user can tap the "Pick Document" button to select a PDF file. The delegate methods will allow you to handle the selected document accordingly.
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?