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



方法在iOS 14中已弃用,因此需要支持iOS 14和更高版本。iOS 13及更早版本

下面是用Swift 5编写的完整代码支持较早版本的iOS 14和更高版本的

此方法已从iOS 14中弃用

public init(documentTypes allowedUTIs: [String], in mode: UIDocumentPickerMode)
  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)
    }
    
  2. 实现代表

//MARK: - UIDocumentPickerDelegate Methods

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)
}
}

相关内容

  • 没有找到相关文章

最新更新