7

I am trying to create a folder in my assets, then get a list of files inside. Sounds simple but there is no clean answer on how to do exactly this.

  1. Even to get the list from the main directory, most people can't do on Swift 3, reading here : Getting list of files in documents folder

using :

let fileMngr = FileManager.default;

// Full path to documents directory
let docs = fileMngr.urls(for: .documentDirectory, in: .userDomainMask)[0].path

// List all contents of directory and return as [String] OR nil if failed
return try? fileMngr.contentsOfDirectory(atPath:docs)

Not working.

  1. Reading from a specific folder, I couldn't understand how to get it's path for swift.

Any example that really work that reads from a folder ?

aturan23
  • 4,798
  • 4
  • 28
  • 52
Curnelious
  • 1
  • 16
  • 76
  • 150
  • 4
    What is not working? Why do you ignore a potential error with `try?`. Please remember that SO is not a code factory for people who are too lazy to learn something (for example reading the documentation) – vadian Jan 25 '18 at 09:54

3 Answers3

17

If you want to get all files in a personal directory, here is the simple answer

    do {
        let documentURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
        let Path = documentURL.appendingPathComponent("yourDirectoyName").absoluteURL
        let directoryContents = try FileManager.default.contentsOfDirectory(at: Path, includingPropertiesForKeys: nil, options: [])
    }
    catch {
        print(error.localizedDescription)
    }

And then if you want for example to read all files with special extension, you can do it that way

static func listAllFileNamesExtension(nameDirectory: String, extensionWanted: String) -> (names : [String], paths : [URL]) {

    let documentURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
    let Path = documentURL.appendingPathComponent(nameDirectory).absoluteURL

    do {
        try FileManager.default.createDirectory(atPath: Path.relativePath, withIntermediateDirectories: true)
        // Get the directory contents urls (including subfolders urls)
        let directoryContents = try FileManager.default.contentsOfDirectory(at: Path, includingPropertiesForKeys: nil, options: [])

        // if you want to filter the directory contents you can do like this:
        let FilesPath = directoryContents.filter{ $0.pathExtension == extensionWanted }
        let FileNames = FilesPath.map{ $0.deletingPathExtension().lastPathComponent }

        return (names : FileNames, paths : FilesPath);

    } catch {
        print(error.localizedDescription)
    }

    return (names : [], paths : [])
}

So if you want to have all your json files in your personal directory

let allJsonNamePath = listAllFileNamesExtension(nameDirectory:"yourDirectoryName", extensionWanted: "json")
Sacha.R
  • 394
  • 2
  • 17
  • not sure how to use your answer, how would I read all files in a folder named "me" in one line ? – Curnelious Jan 25 '18 at 09:59
  • it prints nothing althouh i have a folder full of png files. – Curnelious Jan 25 '18 at 10:02
  • I just edited the post for a more simple answer if you just want all the file in a directory – Sacha.R Jan 25 '18 at 10:05
  • 1
    I just edited the working compilation version. I did this in a rush yesterday But you should really try to resolve errors by yourself, the errors were really not big. – Sacha.R Jan 26 '18 at 08:13
  • 1
    @Curnelious SO isn't a code writing service - it's a place to learn. If the code in the answer isn't compiling, maybe try and fix it before complaining? Look at the code and see what it's trying to achieve and then use that information to write something yourself. – Ashley Mills Jan 26 '18 at 10:06
  • New folder has to be added with: "New Group with Folder" – sabiland Jan 15 '20 at 06:21
9

Swift 4/5

let documentDirectoryPath:String = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
let myFilesPath = "\(documentDirectoryPath)/myfolder"
let filemanager = FileManager.default
let files = filemanager.enumerator(atPath: myFilesPath)
while let file = files?.nextObject() {
    print(file)
}
aturan23
  • 4,798
  • 4
  • 28
  • 52
Mike Zriel
  • 1,575
  • 1
  • 17
  • 28
2

Actually, amazingly, for 2 days no one could tell me the real issue here. Creating a group, is completely different from dragging a folder into the project.

For some reason, with Apple, its always complicated with files. I have to figure out the NOT so intuitive approach that a group that looks like a folder, is nothing but a nice way to look at something, and will not create a real folder accessible by the file manager.

This strange approach is maybe intutitive to a very pro programmer, but really not to any simple person.

Simply put, create a blue folder outside Xcode and drag it in.

Curnelious
  • 1
  • 16
  • 76
  • 150
  • 6
    Maybe if you weren't so rude in your questions and comments, people would be quicker to help you. – Ashley Mills Jan 26 '18 at 09:46
  • @AshleyMills fwiw I do not find his comments rude. He's a bit frustrated: the difference is important because your comment indicates he is lashing out at people – WestCoastProjects May 18 '20 at 19:27
  • @javadba You can't see the history here… _many_ comments from the OP were reported and deleted (he's on a 10 year suspension now, by the look of it) – Ashley Mills May 19 '20 at 10:51
  • OK - clearly I can't determine without the evidence present. Multiple comments reported is _not good_ .. I saw that suspension - wow .. – WestCoastProjects May 19 '20 at 14:58