Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get File List from sub folder of Documents Directory swift ios

I am using this code to get list of PDF files from documents directory. Now I want to find list of PDF files from Folder named "MyFiles" in Document Directory if that folder exists.

How can I do this??

func listFilesFromDocumentsFolder() -> [String]
{
    var theError = NSErrorPointer()
    let dirs = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) as? [String]

    if dirs != nil {
        let dir = dirs![0]
        let fileList = NSFileManager.defaultManager().contentsOfDirectoryAtPath(dir, error: theError) as! [String]
        var count = fileList.count
        for var i = 0; i < count; i++
        {
            var filePath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first as! String
            filePath = filePath.stringByAppendingPathComponent(fileList[i])
            let properties = [NSURLLocalizedNameKey, NSURLCreationDateKey, NSURLContentModificationDateKey, NSURLLocalizedTypeDescriptionKey]
            var attr = NSFileManager.defaultManager().attributesOfItemAtPath(filePath, error: NSErrorPointer())
        }
        return fileList.filter{ $0.pathExtension == "pdf" }.map{ $0.lastPathComponent } as [String]
    }else{
        let fileList = [""]
        return fileList
    }
}

Thanks in advance..

like image 528
Riddhi Shah Avatar asked Jan 06 '23 12:01

Riddhi Shah


1 Answers

I think this may be possible by implementing an extension to NSFileManager that implements the SequenceType protocol. But you could easily convert your code to using a while loop:

// path to documents directory
let documentDirectoryPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first as! String
let myFilesPath = documentDirectoryPath.stringByAppendingPathComponent("/MyFiles")
let files = filemanager.enumeratorAtPath(myFilesPath)
while let file = files?.nextObject() {
     println(file)
}
like image 110
typedef Avatar answered Jan 09 '23 21:01

typedef