Swift/기타
[SWIFT]UIDocumentPickerViewController PDF 문서 멀티선택 첨부
삽질중
2023. 9. 25. 09:18
[Info.plist] 추가
- ApplicationSupports iTunes file sharing : YES
- Supports opening documents in place : YES
import UIKit
import UniformTypeIdentifiers
import MobileCoreServices
class PDFDocsAttach: NSObject {
static let shared = PDFDocsAttach()
var pdfDataClosur: ((_ pdfDatas: [Data]) -> Void)?
override init() {
super.init()
}
class func show() {
guard let topVC = UIApplication.currentTopViewController() else {
return
}
var documentPicker: UIDocumentPickerViewController!
if #available(iOS 14, *) {
documentPicker = UIDocumentPickerViewController(forOpeningContentTypes: [UTType.pdf])
} else {
documentPicker = UIDocumentPickerViewController(documentTypes: [kUTTypePDF as String], in: .import)
}
documentPicker.delegate = shared
documentPicker.allowsMultipleSelection = true
documentPicker.modalPresentationStyle = .overFullScreen//.formSheet
topVC.present(documentPicker, animated: true)
}
}
extension PDFDocsAttach: UIDocumentPickerDelegate {
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
var pdfDatas: [Data] = []
for url in urls {
// Make sure you release the security-scoped resource when you finish.
defer {
url.stopAccessingSecurityScopedResource()
}
// Start accessing a security-scoped resource.
guard url.startAccessingSecurityScopedResource() else {
// Handle the failure here.
return
}
do {
let data = try Data.init(contentsOf: url)
pdfDatas.append(data)
// You will have data of the selected file
}
catch let error {
log(direction: .ERROR, ofType: self, datas: error.localizedDescription)
}
}
PDFDocsAttach.shared.pdfDataClosur?(pdfDatas)
}
func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
controller.dismiss(animated: true, completion: nil)
}
}
[사용방법]
PDFDocsAttach.show()
PDFDocsAttach.shared.pdfDataClosur = { pdfs in
for i in 0..<pdfs.count {
FileSaveManager.fileSave(fileName: "\(i+1).pdf", data: pdfs[i])
}
}