1

I created a UIDocumentPickerViewController and picked my folder on USB drive, after listing files with an enumerator, how can i read the contents?

Are you able to read the contents of a file?

Here is my sample code:

@IBAction func openFiles(_ sender: Any) {

        // Using the Document Picker to Pick a Folder
        let documentPicker = UIDocumentPickerViewController(documentTypes: [kUTTypeFolder as String], in: .open)
        documentPicker.delegate = self
        documentPicker.shouldShowFileExtensions = true
        present(documentPicker, animated: true, completion: nil)
    }

@IBAction func readFiles(){  
        // Reading the Content of a Picked Folder  
        let shouldStopAccessing = pickedFolderURL.startAccessingSecurityScopedResource()  
        defer {  
            if shouldStopAccessing {  
                pickedFolderURL.stopAccessingSecurityScopedResource()  
            }  
        }  
        var coordinatedError:NSError?  
        NSFileCoordinator().coordinate(readingItemAt: pickedFolderURL, error: &coordinatedError) { (folderURL) in  
            let keys : [URLResourceKey] = [.nameKey, .isDirectoryKey]  
            let fileList = FileManager.default.enumerator(at: pickedFolderURL, includingPropertiesForKeys: keys)!  
            logString = ""  
            for case let file as URL in fileList {  

                let newFile = file.path.replacingOccurrences(of: pickedFolderURL.path, with: "")  
                if(newFile.hasPrefix("/.") == false){ //exclude hidden  

                    print(file)  
                    logString += "\n\(file)"  
                    if (file.pathExtension == "mp4"){  
                        self.pickedVideoURL = file  
                    }  
                    if (file.pathExtension == "txt"){  
                        self.pickedTextURL = file  
                    }  
                }  
            }  
            self.logTextView.text = logString  
        }  
    }  

now i want to read the contents of the txt/mp4 file... how? Using quicklook or AVPlayerViewController I get reading errors...

Have you sample project?

Fabiosoft
  • 1,141
  • 14
  • 32
  • I have almost the exact same question here -- https://stackoverflow.com/questions/60498625/reading-files-from-external-storage-in-ios-13 – Kal Mar 03 '20 at 14:23
  • you must use combination of securityScope and coordinator. – Fabiosoft Mar 03 '20 at 15:03

1 Answers1

1

Solution is to use a combination of securityScope and file NSFileCoordinator

@IBAction func readFiles(){
        // Reading the Content of a Picked Folder
 // pickedFolderURL must be a fileURL
        let shouldStopAccessing = pickedFolderURL.startAccessingSecurityScopedResource()
        defer {
            if shouldStopAccessing {
                pickedFolderURL.stopAccessingSecurityScopedResource()
            }
        }
        var coordinatedError:NSError?
        NSFileCoordinator().coordinate(readingItemAt: pickedFolderURL, error: &coordinatedError) { (folderURL) in
            let keys : [URLResourceKey] = [.nameKey, .isDirectoryKey]
            let fileList = FileManager.default.enumerator(at: pickedFolderURL, includingPropertiesForKeys: keys)!
            for case let file as URL in fileList {

                guard pickedFolderURL.startAccessingSecurityScopedResource() else {
                    fatalError("Handle the failure here.")
                    return;
                }        
                // Make sure you release the security-scoped resource when you are done.
                defer { pickedFolderURL.stopAccessingSecurityScopedResource() }

                let newFile = file.path.replacingOccurrences(of: pickedFolderURL.path, with: "")
                if(newFile.hasPrefix("/.") == false){ //exclude hidden
                    print(file)
                }
            }
            self.logTextView.text = logString
        }
    }
Fabiosoft
  • 1,141
  • 14
  • 32
  • Did you mean to `guard pickedFolderURL` again or `guard file` ? Either way -- I tried security scoping the files and always end up in the `fatalError` section – Kal Mar 04 '20 at 01:11
  • scoping the folder will give you access to entire subfolder recursively... i think the mistake is elsewhere – Fabiosoft Mar 05 '20 at 21:59
  • @Kal anyway i tried this code again and it works without permission error. – Fabiosoft Mar 07 '20 at 00:00