3

I am looking for the code that will allow me to scan a folder in my project, and store all file names with a .jpg extension in an array. This is the code I have to scan the main folder of my xcode project, however how do I store the names of files found inside, within an array?

let filemanager:NSFileManager = NSFileManager()
let files = filemanager.enumeratorAtPath(NSHomeDirectory())
while let file = files?.nextObject() {
    // store all file names with extension (jpg) in array
}
2

2 Answers 2

2
let documentsDirectoryURL =  NSFileManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first as! NSURL

let jpgFilesArray = (NSFileManager.defaultManager().contentsOfDirectoryAtURL(documentsDirectoryURL, includingPropertiesForKeys: nil, options: .SkipsHiddenFiles | .SkipsSubdirectoryDescendants | .SkipsPackageDescendants, error: nil) as! [NSURL]).sorted{$0.lastPathComponent<$1.lastPathComponent}.filter{$0.pathExtension!.lowercaseString == "jpg"}

as a read-only computed property

var jpgFilesArray: [NSURL] {
    return (NSFileManager.defaultManager().contentsOfDirectoryAtURL(documentsDirectoryURL, includingPropertiesForKeys: nil, options: .SkipsHiddenFiles | .SkipsSubdirectoryDescendants | .SkipsPackageDescendants, error: nil) as! [NSURL]).sorted{$0.lastPathComponent<$1.lastPathComponent}.filter{$0.pathExtension!.lowercaseString == "jpg"}
}
Sign up to request clarification or add additional context in comments.

Comments

0

Here's an example of how it works. This function returns an array of all the files URLs in a directory and all its subdirectories from a given path.

func files(atPath: String) -> [NSURL] {
    var urls : [NSURL] = []
    let dirUrl = NSURL(fileURLWithPath: atPath)
    if dirUrl != nil {
        let fileManager = NSFileManager.defaultManager()
        let enumerator:NSDirectoryEnumerator? = fileManager.enumeratorAtURL(dirUrl!, includingPropertiesForKeys: nil, options: nil, errorHandler: nil)
        while let url = enumerator?.nextObject() as! NSURL? {
            if url.lastPathComponent == ".DS_Store" {
                continue
            }
            urls.append(url)
        }
    }
    return urls
}


let allFiles = files("/a/directory/somewhere")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.