2

I want to take the path of the folder or file I selected from Document Picker and move it to the "Folder" of my own application with FileManager. However, I am getting this error.

I want to save an image that I choose to the "Folder" path of my own application.

enter image description here

enter image description here

Error:

“Documents” couldn’t be moved because you don’t have permission to access “Documents”.

I solved this error with these codes. However, I'm still having permission issues.

func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) {
  
    guard url.startAccessingSecurityScopedResource() else {
        // Handle denied access
        return
    }
    defer { url.stopAccessingSecurityScopedResource() }
    
    let fileURL = url
    print("url: \(fileURL)")
    
    fileContent = fileURL
}

When I check the code with breakpoint, there is still return in guard let and the process terminates.

DocumentPicker:

struct DocumentPicker: UIViewControllerRepresentable {
    
    @Binding var fileContent: URL
    
    func makeCoordinator() -> DocumentPickerCoordinator {
        return DocumentPickerCoordinator(fileContent: $fileContent)
    }
    
    func makeUIViewController(context: UIViewControllerRepresentableContext<DocumentPicker>) -> UIDocumentPickerViewController {
        let controller: UIDocumentPickerViewController
        controller = UIDocumentPickerViewController(forOpeningContentTypes: [.text, .pdf, .folder, .jpeg, .png, .gif, .exe, .data], asCopy: true)
        controller.delegate = context.coordinator
        return controller
    }
    
    func updateUIViewController(_ uiViewController: UIDocumentPickerViewController, context: UIViewControllerRepresentableContext<DocumentPicker>) {
    }
}


class DocumentPickerCoordinator: NSObject, UIDocumentPickerDelegate, UINavigationControllerDelegate {
    
    @Binding var fileContent: URL
    
    init(fileContent: Binding<URL>) {
        _fileContent = fileContent
    }
    
    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) {
  
        
        guard url.startAccessingSecurityScopedResource() else {
            // Handle denied access
            return
        }
        defer { url.stopAccessingSecurityScopedResource() }
        
        let fileURL = url
        print("url: \(fileURL)")
        
        fileContent = fileURL
    }
}
Ufuk Köşker
  • 1,288
  • 8
  • 29
  • 1
    You will need to startAccessing fileContent again to open up your sandbox when you actually read from it. Here you are just storing the URL into another variable and stop accessing before you actually read anything from it. – Thomas Deniau Jul 18 '22 at 13:43

0 Answers0