How do I use UIDocumentPicker and manage documents in Swift?

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.

Using UIDocumentPicker in Swift

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.


UIDocumentPicker Swift iOS Development Document Management File Picker