Search code examples
uitableviewdirectoryswift2documentxcode7.1

DocumentsDirectory in UITableView Array for Xcode 7 and Swift 2.0


I have a project I'm working on that creates and saves PDF files locally to the DocumentDirectoy. I've read here on how to view the DocumentDirectory and filtering it for it for PDF files. I want to have the DocumentDirectory files be viewable in a UITableView. I know I have to have an array for that. I saw here on doing this, but can't figure out how to get the DocumentDirectory into an array in Swift 2.0 to display in my UITableView. My PDF files are saving and are viewable in my UIWebView.

My code for viewing my DocumentDirectory PDFs is:

    func itemsInDirectory() {

    // We need just to get the documents folder url
    let documentsUrl =  NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!

    // now lets get the directory contents (including folders)
    do {
        let directoryContents = try NSFileManager.defaultManager().contentsOfDirectoryAtURL(documentsUrl, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions())
        print("Items: \(directoryContents)")

    } catch let error as NSError {
        print(error.localizedDescription)
    }

    // if you want to filter the directory contents you can do like this:
    do {
        let directoryUrls = try  NSFileManager.defaultManager().contentsOfDirectoryAtURL(documentsUrl, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions())
        print(directoryUrls)
        let PDFFiles = directoryUrls.filter(){ $0.pathExtension == "pdf" }.map{ $0.lastPathComponent }
        print("PDF FILES:\n" + PDFFiles.description)
    } catch let error as NSError {
        print(error.localizedDescription)
    }

}

It prints them when I run it. Can someone please help me with converting the DocumentDirectory to an array to view in my UITableView? Thank you.


Solution

  • I figured it out. In my main menu View Controller in the ViewDidLoad() section I added:

        // Get the documents folder url
        let documentsUrl =  NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!
    
        // Filter for PDF only
        do {
            let directoryUrls = try  NSFileManager.defaultManager().contentsOfDirectoryAtURL(documentsUrl, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions())
            let PDFFiles = directoryUrls.filter(){ $0.pathExtension == "pdf" }.map{ $0.lastPathComponent }
    
            // Set TableView array for saved files to DocumentDirectory PDFs
            savedPDFFiles = PDFFiles
            print(savedPDFFiles)
    
        } catch let error as NSError {
            print(error.localizedDescription)
        }
    

    In my other Table View Controller, I set savedPDFFiles as a Global Variable. When loading my Table View Controller, the table shows my DocumentDirectoryfiles by name.