UIDocumentPickerViewController - 'init(documentTypes:in:)' 在 iOS 14.0 中已弃用

Ash*_*iya 12 ios swift uidocumentpickerviewcontroller swift5

该方法从 iOS 14 起已弃用,因此需要 iOS 14 及更高版本的支持。以及 iOS 13 及更早版本。

Ash*_*iya 18

这是用Swift 5编写的完整代码,用于支持早期版本的iOS 14 及更高版本

此方法从 iOS 14 起已弃用

public init(documentTypes allowedUTIs: [String], in mode: UIDocumentPickerMode)
Run Code Online (Sandbox Code Playgroud)
  1. 在按钮操作中写入此代码

    import UniformTypeIdentifiers
    
    @IBAction func importItemFromFiles(sender: UIBarButtonItem) {
    
             var documentPicker: UIDocumentPickerViewController!
             if #available(iOS 14, *) {
                 // iOS 14 & later
                 let supportedTypes: [UTType] = [UTType.image]
                 documentPicker = UIDocumentPickerViewController(forOpeningContentTypes: supportedTypes)
             } else {
                 // iOS 13 or older code
                 let supportedTypes: [String] = [kUTTypeImage as String]
                 documentPicker = UIDocumentPickerViewController(documentTypes: supportedTypes, in: .import)
             }
             documentPicker.delegate = self
             documentPicker.allowsMultipleSelection = true
             documentPicker.modalPresentationStyle = .formSheet
             self.present(documentPicker, animated: true)
         }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 实施代表

// 标记: - UIDocumentPickerDelegate 方法

extension MyViewController: UIDocumentPickerDelegate {
        func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
            
            for url in urls {
                
                // Start accessing a security-scoped resource.
                guard url.startAccessingSecurityScopedResource() else {
                    // Handle the failure here.
                    return
                }
                
                do {
                    let data = try Data.init(contentsOf: url)
                    // You will have data of the selected file
                }
                catch {
                    print(error.localizedDescription)
                }
                
                // Make sure you release the security-scoped resource when you finish.
                defer { url.stopAccessingSecurityScopedResource() }
            }
        }
        
        func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
            controller.dismiss(animated: true, completion: nil)
        }
    }
Run Code Online (Sandbox Code Playgroud)

  • 导入 UniformTypeIdentifiers 以防使用 UTType.image 将其纳入范围 (3认同)