-1

I have folder with many files in documents directory. In my folder I have files with different extensions (jpg, png, mp3, zip). In my code I have stringArray. I want to load all files in someArray and after that add files with .png extension from someArray in stringArray How to do it?

Is it possible to do this? Or I should find another way to load multiple files from documents directory?

I find answer for Load multiple images from the folder or directory. - Swift 4

I tried to use this code from answer:

func loadImagesFromAlbum(folderName:String) -> [String]{

        let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
        let nsUserDomainMask    = FileManager.SearchPathDomainMask.userDomainMask
        let paths               = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
        var theItems = [String]()
        if let dirPath          = paths.first
        {
            let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent(folderName)

            do {
                theItems = try FileManager.default.contentsOfDirectory(atPath: imageURL.path)
                return theItems
            } catch let error as NSError {
                print(error.localizedDescription)
                return theItems
            }
        }
        return theItems
    }

But I can't get files from theItems. Because theItems it a string array. What I do wrong? How to get files from loadImagesFromAlbum?

I tried to use this code:

images = loadImagesFromAlbum(folderName: "/folder1")

But it is not help me. I get only names. But I need to get files.

Update

I use this code to load image from documents directory:

        let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
        let nsUserDomainMask    = FileManager.SearchPathDomainMask.userDomainMask
        let paths               = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
        if let dirPath          = paths.first
        {
            let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent("/folder1/1.png")
            myImageView.image = UIImage(contentsOfFile: imageURL.path)
        }

But I need to load 100 images from /folder1 in var images = [String](). Because I use var images = [String]() to show images: contentVC.imageName = images[index] // and etc...

And the code I use above is not very convenient if I need add 40-100 images.

Update 1

I have this code to load images from my project and show it:

class PageViewController: UIViewController {

override func viewDidLoad() {
        super.viewDidLoad()

            for page in 1...pageNumber[indexPage] {
                images.append("page\(page).png")

            }
}

func getContentViewController(withIndex index: Int) -> ContentViewController? {
        if index < images.count{
            let contentVC = self.storyboard?.instantiateViewController(withIdentifier: "ContentViewController") as! ContentViewController
            contentVC.itemIndex = index
            contentVC.imageName = images[index]

            return contentVC
        }

        return nil
    }
}

import UIKit

class ContentViewController: UIViewController {

    @IBOutlet weak var imageView: UIImageView!
    var itemIndex: Int = 0
    var imageName: String?

    override func viewDidLoad() {
        super.viewDidLoad()

        if let currentImage = imageName{
            imageView.image = UIImage(named: currentImage)

        }

    }

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

But I need to load images from documents directory and show it. How to do it?

user291334
  • 77
  • 1
  • 10
  • It's unclear what you are asking. You cannot load *files* into an array. You could load the **contents** of a file (its `Data` representation) into an array. `contentsOfDirectory` returns an array of string paths which are the locations of the files on disk. – vadian Jul 26 '18 at 08:50
  • @vadian I updated question. Add new code below **Update** title. – user291334 Jul 26 '18 at 09:02
  • It's still unclear. You are talking about 3 different things: The file paths are `String`, the images are `UIImage` – you cannot append an `UIImage` to a `String` array – but the name `imageName` implies that it expects only the file name (the last path component) of the file path. – vadian Jul 26 '18 at 09:07
  • @vadian I updated my question. And I asked new question below **Update 1** title. Please tell me if my question is not clear. – user291334 Jul 26 '18 at 09:40

1 Answers1

2

If I understand your question correctly you want to load an image for a specific name in a specific folder in the Documents folder.

Please try this, the method takes two parameters, the file name (with extension!) and the folder name and returns an UIImage or nil if the image cannot be found or created.

func loadImage(withName name : String, from folderName: String) -> UIImage? {
    do {
        let documentsFolderURL = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
        let imageURL = documentsFolderURL.appendingPathComponent(folderName).appendingPathComponent(name)
        let data = try Data(contentsOf: imageURL)
        return UIImage(data: data)
    } catch {
        return nil
    }
}

There is no benefit to get all file paths with contentsOfDirectory because you have to load the image data one by one anyway.

vadian
  • 274,689
  • 30
  • 353
  • 361
  • Thank you! This code work fine. I use this code `let currentImage = loadImage(withName: imageName!, from: "/folder")` `imageView.image = currentImage` in contentViewController. Is it the right usage? – user291334 Jul 27 '18 at 06:17
  • Yes, but you don't need the leading `/`. `appendingPathComponent` handles the path separators. – vadian Jul 27 '18 at 06:21