Search code examples
iosswift

Getting list of files in documents folder


What is wrong with my code for getting the filenames in the document folder?

func listFilesFromDocumentsFolder() -> [NSString]?{
    var theError = NSErrorPointer()
    let dirs = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) as? [String]
    if dirs != nil {
        let dir = dirs![0] as NSString
        let fileList = NSFileManager.defaultManager().contentsOfDirectoryAtPath(dir, error: theError) as [NSString]
        return fileList
    }else{
        return nil
    }
}

I thought I read the documents correctly and I am very sure about what is in the documents folder, but "fileList" does not show anything? "dir" shows the path to the folder.


Solution

  • This solution works with Swift 4 (Xcode 9.2) and also with Swift 5 (Xcode 10.2.1+):

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

    Here's a reusable FileManager extension that also lets you skip or include hidden files in the results:

    import Foundation
    
    extension FileManager {
        func urls(for directory: FileManager.SearchPathDirectory, skipsHiddenFiles: Bool = true ) -> [URL]? {
            let documentsURL = urls(for: directory, in: .userDomainMask)[0]
            let fileURLs = try? contentsOfDirectory(at: documentsURL, includingPropertiesForKeys: nil, options: skipsHiddenFiles ? .skipsHiddenFiles : [] )
            return fileURLs
        }
    }
    
    // Usage
    print(FileManager.default.urls(for: .documentDirectory) ?? "none")