【问题标题】:UIDocumentPickerViewController - 'init(documentTypes:in:)' was deprecated in iOS 14.0UIDocumentPickerViewController - 'init(documentTypes:in:)' 在 iOS 14.0 中已弃用
【发布时间】:2021-11-02 09:00:43
【问题描述】:

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

【问题讨论】:

    标签: ios swift swift5 uidocumentpickerviewcontroller


    【解决方案1】:

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

    iOS 14 已弃用此方法

    public init(documentTypes allowedUTIs: [String], in mode: UIDocumentPickerMode)
    
    1. 在您的按钮操作中编写此代码

      @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)
           }
      
    2. 实现委托

    // MARK: - 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)
            }
        }
    

    【讨论】:

      猜你喜欢
      • 2021-01-23
      • 1970-01-01
      • 1970-01-01
      • 2017-05-02
      • 1970-01-01
      • 2022-01-20
      • 1970-01-01
      • 2021-02-15
      • 2021-10-18
      相关资源
      最近更新 更多