@IBAction func pickerButton(_ sender: UIButton) {
var documentPicker: UIDocumentPickerViewController!
if #available(iOS 14, *) {
documentPicker = UIDocumentPickerViewController(forOpeningContentTypes: [UTType.pdf])
} else {
documentPicker = UIDocumentPickerViewController(documentTypes: [kUTTypePDF as String], in: .import)
}
documentPicker.delegate = self
documentPicker.allowsMultipleSelection = false
documentPicker.modalPresentationStyle = .overFullScreen//.formSheet
self.present(documentPicker, animated: true)
}
import UniformTypeIdentifiers
import MobileCoreServices
extension MainViewController: 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)
print("")
// 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)
}
}