0

I've been searching for ways to list all files from all directories and subdirectories using swift.

I've listed candidate solutions below that didn't work. The one method that partially worked listed all the folders in that directory but it could not list files recursively or use path expressions as below.

Here is the code that partially worked:

let filemanager:FileManager = FileManager()
    let files = filemanager.enumerator(atPath: NSHomeDirectory())
    while let file = files?.nextObject() {
        print(file)

the limitations being

  1. I cannot list all the files from all the subdirectories in this directory
  2. I cannot specify a path like "/User/[username]/Desktop/" or anything else.

How can I fix this problem?

Here are links to the answers I tried but did not work

  1. listing all files in a folder recursively with swift
  2. Iterate through files in a folder and its subfolders using Swift's FileManager
Interlated
  • 5,108
  • 6
  • 48
  • 79
Dhanush
  • 53
  • 6
  • Why didn't the linked questions work and what do you really mean with "all directories"? – Joakim Danielson Nov 10 '20 at 08:34
  • When I printed the values to obtain the names all I got was blank values i.e. it printed nothing. By all directories I mean all subdirectories in the user's home directory, like ```Desktop, Downloads and other such directories in the location``` I wish to get the names of all the files from all those subdirectories and their further subdirectories if they have any. – Dhanush Nov 10 '20 at 09:29
  • The accepted answer in your first link should work. – Joakim Danielson Nov 10 '20 at 10:49
  • It should, but it doesn't all I get is ```[ ]``` as the output when I try and print it – Dhanush Nov 10 '20 at 12:26
  • @joakim Danielson Could it be that i'm entering the directory path wrong? i've tried it in 2 ways both of which gave me the same output. this is how i input the path one way was : ```/User/[username]/Desktop/``` and the other was: ```file:///User/[username]/Desktop/``` both of these gave ```[ ]``` as the output – Dhanush Nov 11 '20 at 05:27
  • You have written `/User/...` three times in the answer and comments, the folder is `Users` - if this typo is in your code it could explain some things (are you checking all the error returns?). Something else you might be hitting is the sandbox which prevents arbitrary access to the file system, do you have the sandbox on? You can address both possibilities at once by using a standard open dialog to select the folder; the returned path/URL will be valid and the sandbox will allow access to the selected folder and all it's descendants. HTH – CRD Nov 12 '20 at 01:47
  • I'm sorry the typo was made here, but in the code the path has been set to /Users/... and yes my sandbox is on i'll check that one. Thank you. – Dhanush Nov 12 '20 at 05:50
  • so what permission will I have to provide in my entitlements to allow my /Users/ directory? – Dhanush Nov 12 '20 at 12:33

0 Answers0