0

I have a yellow folder "Group" name "pdfs" in my Xcode directory. I need to list all file URLs PDFs in the folder to list it in my view.

   func listDir(dir: String) {
        // Create a FileManager instance
        
        let fileManager = FileManager.default
        let documentsURL = fileManager.urls(for: .documentDirectory,
                                            in:.userDomainMask)[0].appendingPathComponent(dir)
        do {
            let fileUrls = try fileManager.contentsOfDirectory(at:documentsURL, includingPropertiesForKeys: nil)
            // process files
            print(fileUrls)
        } catch {
            print("Error while enumerating files \(documentsURL.path): \(error.localizedDescription)")
        }

I had this error

Error while enumerating files /Users/user/Library/Developer/CoreSimulator/Devices/EF0F4EB3-CFB0-42F0-B7F5-B36034508BA2/data/Containers/Data/Application/08019A23-FDD9-4FF8-AC1F-2C13CE293BA5/Documents/pdfs: The file “pdfs” couldn’t be opened because there is no such file.

NinjaDeveloper
  • 1,620
  • 3
  • 19
  • 51
  • It's named `bdfs`, not `pdfs` in your screenshot. But, they shouldn't be accessible through that, they are in your Bundle, so use `Bundle.main` to retrieve them. – Larme Feb 20 '21 at 20:48
  • Umm...without looking at any of the other code. The folder that you have screenshot. Shows “bdfs”, not “pdfs” – Paulo Feb 20 '21 at 20:49
  • Either https://stackoverflow.com/questions/40692737/how-to-get-path-to-a-subfolder-in-main-bundle or https://stackoverflow.com/questions/34548771/swift-how-do-i-get-the-file-path-inside-a-folder ? – Larme Feb 20 '21 at 20:50

1 Answers1

0

this the solution from Swift - How do I get the file path inside a folder

make sure to add the blue folder to your code project enter image description here

and the code

    func listDir(dir: String) -> [URL]? {
    let fileManager = FileManager.default
    let documentsURL = Bundle.main.resourceURL!.appendingPathComponent(dir)
    var fileUrls:[URL]?

    do {
        fileUrls = try fileManager.contentsOfDirectory(at:documentsURL, includingPropertiesForKeys: nil)
        return  fileUrls
        
    } catch {
        print("Error while enumerating files \(documentsURL.path): \(error.localizedDescription)")
        return nil
    }
}
NinjaDeveloper
  • 1,620
  • 3
  • 19
  • 51