SwiftUI UIDocumentPickerViewControllerを使用する

2021年8月7日

SwiftUIでUIDocumentPickerViewControllerを使用する

Point

  • final classにする
  • NSObjectをベースに入れる
import SwiftUI
import UIKit
import UniformTypeIdentifiers

final class UIDocumentPickerViewControllerView: NSObject, UIViewControllerRepresentable {
    func makeUIViewController(context: Context) -> UIDocumentPickerViewController {
        let documentPicker = UIDocumentPickerViewController(forOpeningContentTypes: [UTType.jpeg, UTType.png])
        documentPicker.delegate = self
        return documentPicker
    }

    func updateUIViewController(_ controller: UIDocumentPickerViewController, context: Context) {
        print(#function)
    }
}

extension UIDocumentPickerViewControllerView: UIDocumentPickerDelegate {
    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
        guard urls.count != 0 else {
            return
        }
        print(#function)
        print(urls.debugDescription)
    }
}

使用する側Example

:
:
}
.sheet(isPresented: self.$onDocumentPicker, onDismiss: {}, content: {
    UIDocumentPickerViewControllerView()
})

SwiftSwift,SwiftUI

Posted by shi-n