SwiftUI UIDocumentPickerViewControllerで選択したファイルをアプリフォルダにコピーする

SwiftUIでUIDocumentPickerViewControllerで選択したファイルをアプリフォルダにコピーする

Point

  • startAccessingSecurityScopedResource()
import SwiftUI
import UIKit
import UniformTypeIdentifiers

final class UIDocumentPickerViewControllerView: NSObject, UIViewControllerRepresentable {
    @EnvironmentObject var refillData: RefillData
    
    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
        }
        if fileManager.fileExists(atPath: urls[0].absoluteString) == false {
            let _ = urls[0].startAccessingSecurityScopedResource()
            do {
                try fileManager.copyItem(at: urls[0], to: URL(fileURLWithPath: filePath))
            }
            catch let error {
                print(error)
            }
            let _ = urls[0].stopAccessingSecurityScopedResource()
        }
    }
}

使用する側Example

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