sahil saini
sahil saini

Reputation: 11

swift how to get all files from a sub folder we created in document directory?

let fileManager = FileManager.default
            let documentsFolder = try! fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
            do{
                let contents = try FileManager.default.contentsOfDirectory(at: documentsFolder,includingPropertiesForKeys: nil,options: [.skipsHiddenFiles])[0]
                print(contents)
                let directoryContents = try! fileManager.contentsOfDirectory(at: contents, includingPropertiesForKeys: nil)
                let item = directoryContents[indexPath.row]
                let photoURL = URL.init(fileURLWithPath: item.path)

                let data = try? Data(contentsOf: photoURL)
                let image = UIImage(data: data!)
                cell.imageView.image = image


                    } catch let error as NSError {
                        print("Error: \(error.localizedDescription)")
                    }
                    }

Upvotes: 0

Views: 687

Answers (1)

Celeste
Celeste

Reputation: 1577

You can manually do this like this :

 let fileManager = FileManager.default
 let documentsFolder = try! fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)


    let subdirectories = try? fileManager.contentsOfDirectory(atPath: documentsFolder.path) 
     // this will give the last component only.

  for subdirectory in subDirectories {

        let photoPath = documentsFolder + “/“ + subdirectory + “/“ + fileManager.contentsOfDirectory(atPath : subdirectory)[indexPath.item]
        let photoURL = URL.init(fileURLWithPath: photoPath)

            let data = try? Data(contentsOf: photoURL)
            let image = UIImage(data: data!)
            cell.imageView.image = image


    }

Upvotes: 2

Related Questions