Search code examples
arraysswiftnsfilemanager

How do I get an array of file names from the iOS File Manager


I'm creating an Audio Recording app and have declared an empty array to store all the names of the files.

var recordingTitles: [String] = []

When I launch the app, I have a function that checks what files are already stored in the File Manager and returns the number of files in order to display the correct number of cells in the collectionView.

override func viewDidLoad() {
    super.viewDidLoad()
    getNumberOfRecordings()

}

// Get number of actual recording files stored in the File Manager Directory
func getNumberOfRecordings() {
    let directoryUrl = getDirectory()

    do {
        contentsOfFileManager = try myFileManager.contentsOfDirectory(at: directoryUrl, includingPropertiesForKeys: [URLResourceKey(rawValue: recordingsKey)], options: .skipsHiddenFiles)

    } catch let error {
        print(error.localizedDescription)
    }
    numberOfRecordings = contentsOfFileManager.count
}

I would like to obtain the names of the files and assign them to the "recordingTitles" array in order to display the correct title for each cell. I've tried reading over the Apple docs for File Manager but haven't found a solution yet. Thank you in advance for your help!


Solution

  • So, contentsOfFileManager is going to consist of NSURL objects. These objects have different fields you can pluck out and use. It looks like you're interested in just the filename so I'd like to draw your attention to the lastPathComponent field of NSURL. From the docs:

    This property contains the last path component, unescaped using the replacingPercentEscapes(using:) method. For example, in the URL file:///path/to/file, the last path component is file.

    In other words, calling myNsurl.lastPathComponent should yield you the filename. So you can loop through the array that's returned by myFileManager.contentsOfDirectory and get the lastPathComponent of each one and add them to another array which will contain just the filenames.