Search code examples
iosswiftfile-management

list all file URLs in xCode Group


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.


Solution

  • 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
        }
    }