Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSFileManager - Swift - File Browser

I am new at ios development and I am trying to create an app in swift that will list all the files in the directory (all the files are PDF) and the user to be able to open them.

I have googling this for a the past two days and I am super confused. Can anyone suggest a tutorial or steps I would need to get this to work.

I have started with this in my ViewController.swift file:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    class func defaultManager()->NSFileManager{

    }

}

I just don't know what to do next, very sad I know. I would appreciate any or all help.

Thanks, J

like image 784
user3608800 Avatar asked Jan 10 '23 15:01

user3608800


2 Answers

let manager = NSFileManager.defaultManager()
var array = manager.contentsOfDirectoryAtPath(_ path: String,
                         error error: NSErrorPointer) -> [AnyObject]?

Swift 3.0 version

let manager = FileManager.default
let installed_files = try manager.contentsOfDirectory(atPath: "/Applications/")
like image 123
Nicolas Manzini Avatar answered Jan 12 '23 03:01

Nicolas Manzini


Here is a more complete example and updated for Swift 2.

Add your files to a Folder (not a Group) in your project. Then use the following code to get a list of file names.

private func getListOfFileNames() -> Array<String> {

    let docsPath = NSBundle.mainBundle().resourcePath! + "/DirectoryName"
    let fileManager = NSFileManager.defaultManager()
    let docsArray: Array<String>

    do {
        docsArray = try fileManager.contentsOfDirectoryAtPath(docsPath)
    } catch {
        print(error)
    }

    return docsArray
}
like image 30
Suragch Avatar answered Jan 12 '23 05:01

Suragch