swiftnsdocumentdirectorydocument-directory

How do I get list of Images saved in a folder?


I have to get list of images, which i have saved in a directory as a sub-directory. First i created a document directory, then inside i have some folders, In the folder i have saved images(like sub-directory). Now i want to get list of images to show on a UITableView.

I used following code to save

func saveImageToDocumentDirectory(image: UIImage ) {
    let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
    let fileName = txtfield.text! + ".png"
    let fileURL = documentsDirectory.appendingPathComponent(directoryName).appendingPathComponent(fileName)
    
    if let data = image.jpegData(compressionQuality: 1.0),!FileManager.default.fileExists(atPath: fileURL.path){
        do {
            try data.write(to: fileURL)
            print("file saved")
            fileNameArray.append(fileName)
        } catch {
            print("error saving file:", error)
        }
    }
}

So, Now I want to get list of images saved here.


Solution

  • The same way you're appending directoryName when composing your fileURL, you can get directoryURL and read its files:

    let fileManager = FileManager.default
    let documentsURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
    let directoryURL = documentsURL.appendingPathComponent(directoryName)
    do {
        let fileURLs = try fileManager.contentsOfDirectory(at: directoryURL, includingPropertiesForKeys: nil)
        // process files
    } catch {
        print(error)
    }