iOS/코드조각
[iOS, Swift] DocumentPicker 사용예제
검은참깨두유vm
2023. 2. 20. 19:32
반응형
iOS 16.1, Xcode 14.2, Swift 5, UIKit 환경에서 진행했습니다.
DocumentPickerController에서 forOpeningContentTypes의 타입을 설정하고 초기화를 한 후
present로 pickerController를 띄어준다.설정된 타입은 png로 하였는데, png 파일만 선택이 가능하게끔 됩니다.
import MobileCoreServices
import UniformTypeIdentifiers
@IBAction func didTapDocument(_ sender: UIButton) {
let types = UTType(tag: "png", tagClass: UTTagClass.filenameExtension, conformingTo: nil)
let documentPickerController = UIDocumentPickerViewController(forOpeningContentTypes: [types!])
documentPickerController.delegate = self
self.present(documentPickerController, animated: true, completion: nil)
}
Delegate는 Document 클릭 시 등의 DocumentPicker에 대한 설정을 할 수 있습니다.
extension MainViewController: UIDocumentPickerDelegate, UINavigationControllerDelegate {
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
print("didPickDocumentsAt = \(urls)")
}
}
설정은 프로젝트 설정 - Signing & Capablilities에 +Capablity에서 iCloud를 추가한 뒤에
아래와 같이 Key-value storage를 선택하면 됩니다.

전체코드
class ViewController: UIViewController {
...
@IBAction func didTapDocument(_ sender: UIButton) {
let types = UTType(tag: "png", tagClass: UTTagClass.filenameExtension, conformingTo: nil)
let documentPickerController = UIDocumentPickerViewController(forOpeningContentTypes: [types!])
documentPickerController.delegate = self
self.present(documentPickerController, animated: true, completion: nil)
}
}
extension ViewController: UIDocumentPickerDelegate, UINavigationControllerDelegate {
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
print("didPickDocumentsAt = \(urls)")
}
}
결과

참조
https://stackoverflow.com/questions/37296929/implement-document-picker-in-swift-ios
반응형